CWIS Developer Documentation
Resource--Test.php
Go to the documentation of this file.
1 <?PHP
2 
3 class Resource_Test extends PHPUnit\Framework\TestCase
4 {
11  public static function setUpBeforeClass()
12  {
13  # construct the schema object
15 
16  self::$TestFieldIds = array();
17 
18  # outline fields to be created
19  self::$TestFields = array(
20  "Test Text Field" => MetadataSchema::MDFTYPE_TEXT,
21  "Test Timestamp Field" => MetadataSchema::MDFTYPE_TIMESTAMP,
22  "Test Paragraph Field" => MetadataSchema::MDFTYPE_PARAGRAPH,
23  "Test Url Field" => MetadataSchema::MDFTYPE_URL,
24  "Test Reference Field" => MetadataSchema::MDFTYPE_REFERENCE,
25  "Test User Field" => MetadataSchema::MDFTYPE_USER,
26  "Test Option Field" => MetadataSchema::MDFTYPE_OPTION,
27  "Test CName Field" => MetadataSchema::MDFTYPE_CONTROLLEDNAME,
28  "Test Tree Field" => MetadataSchema::MDFTYPE_TREE,
29  "Test Date Field" => MetadataSchema::MDFTYPE_DATE,
30  "Test Flag Field" => MetadataSchema::MDFTYPE_FLAG,
31  "Test Number Field" => MetadataSchema::MDFTYPE_NUMBER,
32  "Test Point Field" => MetadataSchema::MDFTYPE_POINT,
33  );
34 
35  # create the fields
36  foreach (self::$TestFields as $FieldName => $FieldType)
37  {
38  $TmpField = $Schema->GetItemByName($FieldName);
39  if ($TmpField === NULL)
40  {
41  $TmpField = $Schema->AddField($FieldName, $FieldType);
42  }
43  $TmpField->IsTempItem(FALSE);
44  self::$TestFieldIds[$FieldName] = $TmpField->Id();
45  }
46 
47  # Resource::Create() expects a user to be logged in,
48  # so log in an admin user
49  $UFactory = new CWUserFactory();
50  $Users = $UFactory->GetUsersWithPrivileges(
51  PRIV_RESOURCEADMIN, PRIV_COLLECTIONADMIN);
52  $UserIds = array_keys($Users);
53  $AdminUserId = array_pop($UserIds);
54  self::$AdminUser = new CWUser($AdminUserId);
55  $GLOBALS["G_User"]->Login(self::$AdminUser->Name(), "", TRUE);
56 
57  # Create Classification, ControlledName, and Option values
58  self::$TestClassification = Classification::Create(
59  "Test Classification", self::$TestFieldIds['Test Tree Field']);
60  self::$TestControlledName = ControlledName::Create(
61  "Test Controlled Name", self::$TestFieldIds['Test CName Field']);
62  self::$TestOptionCName = ControlledName::Create(
63  "Test Option Name", self::$TestFieldIds['Test Option Field']);
64  }
65 
70  public static function tearDownAfterClass()
71  {
72  # construct the schema object
73  $Schema = new MetadataSchema();
74  $Database = new Database();
75 
76  # drop all of the test fields
77  foreach (self::$TestFieldIds as $FieldName => $FieldId)
78  {
79  $Schema->DropField($FieldId);
80  }
81 
82  self::$TestClassification->Delete();
83  self::$TestControlledName->Delete();
84  self::$TestOptionCName->Delete();
85  }
86 
91  public function testResource()
92  {
93  # create test-specific objects
95  $this->assertTrue($TestResource->IsTempResource(),
96  "Check that newly created resources are temporary.");
97 
98  $this->assertFalse($TestResource->IsTempResource(FALSE),
99  "Check resources can be set permanent.");
100 
101  # test Comments features
102  $this->CheckComments($TestResource);
103 
104  # test Ratings features
105  $this->CheckRatings($TestResource);
106 
107  # test permissions-related functions
108  $this->CheckPermissions($TestResource);
109 
110  # test get, set, and clear
111  $TestReferenceResource = Resource::Create(MetadataSchema::SCHEMAID_DEFAULT);
112  $TestReferenceResource->IsTempResource(FALSE);
113  $this->CheckGetSetClear($TestResource, $TestReferenceResource);
114 
115  # check that resource schemas can be retrieved
116  $this->CheckGetSchemaForResource(
117  $TestResource, $TestReferenceResource);
118 
119  # check that GetAsArray works
120  $this->CheckGetAsArray(
121  $TestResource, $TestReferenceResource);
122 
123  # check that perm resource can be made temporary and don't
124  # lose any values in the process
125  $this->CheckTempToggle($TestResource);
126 
127 
128  # clean up function-specific objects
129  $TestResource->Delete();
130  $TestReferenceResource->Delete();
131  }
132 
138  private function CheckGetSetClear($Resource, $RefResource)
139  {
140  # test get, set, and clear for each test field
141  foreach (self::$TestFieldIds as $FieldName => $FieldId)
142  {
143  $Field = new MetadataField($FieldId);
144 
145  # whether, before testing equivalence, we need to pop the
146  # returned value out of an array
147  $BeforeTestArrayShift = FALSE;
148 
149  # if we're testing the object return, this is the object we'll compare it to.
150  unset($TestObject);
151 
152  switch ($Field->Type())
153  {
155  $TgtVal = "A test title";
156  break;
157 
159  $TgtVal = "http://testtesttest.com";
160  break;
161 
163  $TgtVal = "I am a test paragraph.";
164  break;
165 
167  $TgtVal = "0";
168  break;
169 
171  $TgtVal = "1";
172  break;
173 
175  $TgtVal = date("Y-m-d");
176  $TestObject = new Date(strval($TgtVal));
177  $TestObjectType = 'Date';
178  $TestFunctionName = 'BeginDate';
179  $TestFunctionArguments = NULL;
180  break;
181 
183  $TgtVal = date("Y-m-d H:i:s");
184  break;
185 
187  $TgtVal = array();
188  $TgtVal[self::$TestClassification->Id()] = "Test Classification";
189  $TestObject = self::$TestClassification;
190  $TestObjectType = 'Classification';
191  $TestFunctionName = 'FullName';
192  $TestFunctionArguments = NULL;
193  $BeforeTestArrayShift = TRUE;
194  break;
195 
197  $TgtVal = array();
198  $TgtVal[self::$TestControlledName->Id()] = "Test Controlled Name";
199  $TestObject = self::$TestControlledName;
200  $TestObjectType = 'ControlledName';
201  $TestFunctionName = 'Name';
202  $TestFunctionArguments = NULL;
203  $BeforeTestArrayShift = TRUE;
204  break;
205 
207  $TgtVal = array();
208  $TgtVal[self::$TestOptionCName->Id()] = "Test Option Name";
209  $TestObject = self::$TestOptionCName;
210  $TestObjectType = 'ControlledName';
211  $TestFunctionName = 'Name';
212  $TestFunctionArguments = NULL;
213  $BeforeTestArrayShift = TRUE;
214  break;
215 
217  $UserId = $GLOBALS["G_User"]->Id();
218  $TestObject = new CWUser($UserId);
219  $TgtVal = array( $UserId => $TestObject->Name() );
220  $TestObjectType = 'CWUser';
221  $TestFunctionName = 'Id';
222  $TestFunctionArguments = NULL;
223  $BeforeTestArrayShift = TRUE;
224  break;
225 
227  $TgtVal = array();
228  $TgtVal['X'] = 5;
229  $TgtVal['Y'] = 7;
230  break;
231 
233  $TestObject = $RefResource;
234  $TgtVal = array();
235  $TgtVal[$RefResource->Id()] = $RefResource->Id();
236  $TestFunctionName = 'Id';
237  $TestObjectType = 'Resource';
238  $TestFunctionArguments = NULL;
239  $BeforeTestArrayShift = TRUE;
240  break;
241 
242  default:
243  throw new Exception("Data type not handled.");
244  break;
245 
246  }
247 
248  # set the value on the test resource
249  $Resource->Set($Field, $TgtVal);
250 
251  # assert the default get returns the expected value
252  $FieldTypeName = StdLib::GetConstantName(
253  "MetadataSchema", $Field->Type(), "MDFTYPE_");
254  $this->assertEquals($TgtVal, $Resource->Get($Field),
255  "Check that value returned by Get() matches for field type "
256  .$FieldTypeName);
257 
258  $this->assertTrue($Resource->FieldIsSet($Field),
259  "Check that FieldIsSet() returns TRUE after setting value for field type "
260  .$FieldTypeName);
261 
262  $RCopy = new Resource($Resource->Id());
263  $this->assertEquals($TgtVal, $RCopy->Get($Field),
264  "Check that value returned by Get() matches for field type w/ new resource"
265  .$FieldTypeName);
266 
267  if (isset($TestObject))
268  {
269  $ReturnedObject = $Resource->Get($Field, TRUE);
270 
271  if ($BeforeTestArrayShift)
272  {
273  $ReturnedObject = array_shift($ReturnedObject);
274  }
275 
276  $array_for_test_object = array($TestObject, $TestFunctionName);
277  $array_for_returned_object = array($ReturnedObject, $TestFunctionName);
278 
279  if ($TestFunctionArguments !== NULL)
280  {
281  $this->assertEquals(call_user_func(
282  $array_for_returned_object, $TestFunctionArguments),
283  call_user_func($array_for_test_object, $TestFunctionArguments));
284  }
285  else
286  {
287  $this->assertEquals(call_user_func($array_for_returned_object),
288  call_user_func($array_for_test_object));
289  }
290 
291  $this->assertInstanceOf($TestObjectType, $ReturnedObject);
292  }
293 
294  # clear the value from the field
295  $Resource->Clear($Field);
296 
297  switch ($Field->Type())
298  {
306  $TgtVal = NULL;
307  break;
308 
314  $TgtVal = array();
315  break;
316 
318  $TgtVal = array(
319  "X" => NULL,
320  "Y" => NULL );
321  break;
322 
323  default:
324  throw new Exception("Data type not handled.");
325  break;
326 
327  }
328 
329  $this->assertEquals($TgtVal, $Resource->Get($Field));
330 
331  $this->assertFalse($Resource->FieldIsSet($Field),
332  "Check that FieldIsSet() returns FALSE after clearing value for field type "
333  .$FieldTypeName);
334 
335  $RCopy = new Resource($Resource->Id());
336  $this->assertEquals($TgtVal, $RCopy->Get($Field),
337  "Check that value returned by Get() matches for field type w/ new resource"
338  .$FieldTypeName);
339  }
340  }
341 
347  private function CheckComments($Resource)
348  {
349  $this->assertEquals(0, $Resource->NumberOfComments(),
350  "Check that newly created resources have no comments.");
351  $this->assertNull($Resource->Comments(),
352  "Check that newly created resources have null comment list.");
353 
354  $TestComment = Message::Create();
355  $TestComment->ParentType(Message::PARENTTYPE_RESOURCE);
356  $TestComment->ParentId($Resource->Id());
357 
358  # reload resource to nuke internal caches
359  $Resource = new Resource($Resource->Id());
360 
361  $this->assertEquals(1, $Resource->NumberOfComments(),
362  "Check that NumberOfComments() is one after adding a single comment.");
363 
364  $RComments = $Resource->Comments();
365 
366  $this->assertTrue(is_array($RComments),
367  "Check that Comments() returns an array.");
368 
369  $this->assertEquals(1, count($RComments),
370  "Check that Comments() returns an array of length 1");
371 
372  $RComment = array_Shift($RComments);
373 
374  $this->assertTrue($RComment instanceof Message,
375  "Check that the comment is a Message.");
376 
377  $this->assertEquals($TestComment->Id(), $RComment->Id(),
378  "Check that the CommentId of the single Message in the array returned "
379  ."by Comments() matches the Id of the test comment "
380  ."that we just associated with the resource.");
381 
382  $TestComment->Destroy();
383 
384  # reload resource to nuke internal caches
385  $Resource = new Resource($Resource->Id());
386 
387  $this->assertEquals(0, $Resource->NumberOfComments(),
388  "Check that resource has no comments after deleting comment.");
389  $this->assertNull($Resource->Comments(),
390  "Check that resource has null comment list after deleting comment.");
391  }
392 
398  private function CheckRatings($Resource)
399  {
400  $this->assertEquals(0, $Resource->NumberOfRatings(),
401  "Check that newly created resources have no ratings.");
402  $this->assertEquals(0, $Resource->CumulativeRating(),
403  "Check that newly created resources have no cumulative rating.");
404  $this->assertEquals(0, $Resource->ScaledCumulativeRating(),
405  "Check that newly created resources have no scaled cumulative rating.");
406 
407  # ratings checks
408  $this->assertNull($Resource->Rating(),
409  "Check that admin user hasn't rated this resource.");
410  $this->assertEquals(25, $Resource->Rating(25),
411  "Check that admin user can rate this resource.");
412  $this->assertEquals(25, $Resource->Rating(),
413  "Check that admin's rating was saved");
414  $this->assertEquals(1, $Resource->NumberOfRatings(),
415  "Check that number of ratings is correct.");
416  $this->assertEquals(25, $Resource->CumulativeRating(),
417  "Check that cumulative rating is correct.");
418  $this->assertEquals(3, $Resource->ScaledCumulativeRating(),
419  "Check that scaled cumulative rating is correct.");
420  $this->assertEquals(50, $Resource->Rating(50),
421  "Check that admin can change rating.");
422  $this->assertEquals(1, $Resource->NumberOfRatings(),
423  "Check that number of ratings is correct.");
424  $this->assertEquals(50, $Resource->CumulativeRating(),
425  "Check that cumulative rating is correct.");
426  $this->assertEquals(5, $Resource->ScaledCumulativeRating(),
427  "Check that scaled cumulative rating is correct.");
428 
429  $GLOBALS["G_User"]->Logout();
430  $this->assertNull(
431  $Resource->Rating(),
432  "Check that anon user hasn't rated this resource.");
433  $GLOBALS["G_User"]->Login(self::$AdminUser->Name(), "", TRUE);
434  }
435 
446  private function CheckPermissions($Resource)
447  {
448  $TitleField = $Resource->Schema()->GetFieldByMappedName("Title");
449  foreach (["View", "Edit", "Author", "Modify"] as $Action)
450  {
451  $CheckFn = "UserCan".$Action;
452  $FieldCheckFn = "UserCan".$Action."Field";
453 
454  $this->assertFalse(
455  $Resource->$CheckFn(CWUser::GetAnonymousUser()),
456  "Check that Anon users cannot ".strtolower($Action)
457  ." a new Resource.");
458  $this->assertFalse(
459  $Resource->$FieldCheckFn(CWUser::GetAnonymousUser(), $TitleField),
460  "Check that Anon users cannot ".strtolower($Action)
461  ." the Title field on a new Resource.");
462 
463  $this->assertTrue(
464  $Resource->UserCanView(self::$AdminUser),
465  "Check that admin users can ".strtolower($Action)
466  ." a new Resource.");
467  $this->assertTrue(
468  $Resource->$FieldCheckFn(self::$AdminUser, $TitleField),
469  "Check that admin users can ".strtolower($Action)
470  ." the Title field on a new Resource.");
471  }
472 
473  $this->assertFalse(
474  $Resource->UserCanViewMappedField(CWUser::GetAnonymousUser(), "Title"),
475  "Check that Anon users cannot view mapped Title on a new Resource.");
476 
477  $this->assertFalse(
478  $Resource->UserCanViewField(self::$AdminUser, PHP_INT_MAX),
479  "Check that users cannot view invalid fields.");
480 
481  $Field = $Resource->Schema()->GetField("Test Text Field");
482  $Field->Enabled(FALSE);
483 
484 
485  # do disabled field check on a copy of the resource so that
486  # the PermissionCache doesn't cause it to succeed erroneously
487  $RCopy = new Resource($Resource->Id());
488  $this->assertFalse(
489  $RCopy->UserCanViewField(self::$AdminUser, $Field),
490  "Check that users cannot view disabled fields.");
491  $Field->Enabled(TRUE);
492  }
493 
499  private function CheckGetSchemaForResource($Resource, $RefResource)
500  {
501  $this->assertEquals(
503  Resource::GetSchemaForResource($Resource->Id()),
504  "Check that GetSchemaIdForResource() is correct with a single resource.");
505 
506  try
507  {
508  Resource::GetSchemaForResource(PHP_INT_MAX);
509  $this->assertFalse(
510  TRUE, "GetSchemaForResource() did not throw exception on invalid Id.");
511  }
512  catch (Exception $e)
513  {
514  $this->assertTrue(
515  $e instanceof InvalidArgumentException,
516  "GetSchemaForResource() threw wrong exception type.");
517  }
518 
519  $Ids = [$Resource->Id(), $RefResource->Id()];
520  $this->assertEquals(
521  array_fill_keys($Ids, MetadataSchema::SCHEMAID_DEFAULT),
523  "Check that GetSchemaIdForResource() is correct with multiple resources.");
524 
525  $Ids[]= PHP_INT_MAX;
526  try
527  {
529  $this->assertFalse(
530  TRUE, "GetSchemaForResource() did not throw exception on invalid Id.");
531  }
532  catch (Exception $e)
533  {
534  $this->assertTrue(
535  $e instanceof InvalidArgumentException,
536  "GetSchemaForResource() threw wrong exception type.");
537  }
538  }
539 
545  private function CheckGetAsArray($Resource, $RefResource)
546  {
547  $Values = [
548  "Test Text Field" => "TestValue",
549  "Test Url Field" => "http://example.com",
550  "Test Reference Field" =>
551  [$RefResource->Id() => $RefResource->Id()],
552  "Test User Field" =>
553  [$GLOBALS["G_User"]->Id() => $GLOBALS["G_User"]->Get("UserName")],
554  "Test Option Field" =>
555  [self::$TestOptionCName->Id() => self::$TestOptionCName->Name()],
556  "Test CName Field" =>
557  [self::$TestControlledName->Id() => self::$TestControlledName->Name()],
558  "Test Tree Field" =>
559  [self::$TestClassification->Id() => self::$TestClassification->FullName()],
560  ];
561 
562  foreach ($Values as $FieldName => $Value)
563  {
564  $Resource->Set($FieldName, $Value);
565  }
566 
567  $Result = $Resource->GetAsArray(FALSE, FALSE);
568 
569  # subset to just the fields that we've set
570  $Result = array_intersect_key($Result, $Values);
571 
572  $this->assertEquals(
573  $Values, $Result, "Checking GetAsArray()");
574  }
575 
581  private function CheckTempToggle($Resource)
582  {
583  $this->assertFalse(
584  $Resource->IsTempResource(),
585  "Check that provided resource is permanent.");
586 
587  $Before = $Resource->GetAsArray(TRUE, FALSE);
588 
589  $this->assertTrue(
590  $Resource->IsTempResource(TRUE),
591  "Check that permanent resources can be made temporary.");
592 
593  $After = $Resource->GetAsArray(TRUE, FALSE);
594  unset($Before["ResourceId"]);
595  unset($After["ResourceId"]);
596 
597  $this->assertEquals(
598  $Before, $After,
599  "Check that resource values don't change on perm/temp toggle");
600 
601  $RCopy = new Resource($Resource->Id());
602 
603  $AfterCopy = $RCopy->GetAsArray(TRUE, FALSE);
604  unset($AfterCopy["ResourceId"]);
605 
606  $this->assertEquals(
607  $After, $AfterCopy,
608  "Check that resource values don't change on perm/temp toggle "
609  ."w/ newly loaded resource");
610  }
611 
612  protected static $TestFieldIds;
613  protected static $TestFields;
614  protected static $AdminUser;
615  protected static $TestClassification;
616  protected static $TestControlledName;
617  protected static $TestOptionCName;
618 }
static GetAnonymousUser()
Get the anonymous user (i.e., the User object that exists when no user is logged in), useful when a permission check needs to know if something should be visible to the general public.
Definition: User.php:948
static tearDownAfterClass()
After to running the tests, this function is run.
Metadata schema (in effect a Factory class for MetadataField).
Abstraction for forum messages and resource comments.
Definition: Message.php:14
static $TestControlledName
static Create($Term, $FieldId)
Create a new empty ControlledName if it&#39;s not already present.
static Create()
Create an empty message object.
Definition: Message.php:28
SQL database abstraction object with smart query caching.
Definition: Database.php:22
static Create($Name, $FieldId, $ParentId=NULL)
Add new classification to the hierarchy.
GetAsArray($IncludeDisabledFields=FALSE, $ReturnObjects=TRUE)
Retrieve all resource values as an array.
Definition: Resource.php:828
const PARENTTYPE_RESOURCE
Definition: Message.php:17
Definition: Date.php:18
const MDFTYPE_CONTROLLEDNAME
Comments()
Get comments for resource.
Definition: Resource.php:2177
static setUpBeforeClass()
Prior to running any of the tests, this function is run.
CWIS-specific user factory class.
Get($Field, $ReturnObject=FALSE, $IncludeVariants=FALSE)
Retrieve value using field name or field object.
Definition: Resource.php:420
static GetSchemaForResource($ResourceId)
Get schema ID for specified resource(s).
Definition: Resource.php:2351
static GetConstantName($ClassName, $Value, $Prefix=NULL)
Get name (string) for constant.
Definition: StdLib.php:856
testResource()
This function exercises the Resource get and set methods for each Metadata types using the fields cre...
Object representing a locally-defined type of metadata field.
Represents a "resource" in CWIS.
Definition: Resource.php:13
static $TestClassification
static $TestOptionCName
static Create($SchemaId)
Create a new resource.
Definition: Resource.php:48
CWIS-specific user class.
Definition: CWUser.php:13