You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

488 lines
11 KiB

3 years ago
  1. This is the PHP port of Hamcrest Matchers
  2. =========================================
  3. [![Build Status](https://travis-ci.org/hamcrest/hamcrest-php.png?branch=master)](https://travis-ci.org/hamcrest/hamcrest-php)
  4. Hamcrest is a matching library originally written for Java, but
  5. subsequently ported to many other languages. hamcrest-php is the
  6. official PHP port of Hamcrest and essentially follows a literal
  7. translation of the original Java API for Hamcrest, with a few
  8. Exceptions, mostly down to PHP language barriers:
  9. 1. `instanceOf($theClass)` is actually `anInstanceOf($theClass)`
  10. 2. `both(containsString('a'))->and(containsString('b'))`
  11. is actually `both(containsString('a'))->andAlso(containsString('b'))`
  12. 3. `either(containsString('a'))->or(containsString('b'))`
  13. is actually `either(containsString('a'))->orElse(containsString('b'))`
  14. 4. Unless it would be non-semantic for a matcher to do so, hamcrest-php
  15. allows dynamic typing for it's input, in "the PHP way". Exception are
  16. where semantics surrounding the type itself would suggest otherwise,
  17. such as stringContains() and greaterThan().
  18. 5. Several official matchers have not been ported because they don't
  19. make sense or don't apply in PHP:
  20. - `typeCompatibleWith($theClass)`
  21. - `eventFrom($source)`
  22. - `hasProperty($name)` **
  23. - `samePropertyValuesAs($obj)` **
  24. 6. When most of the collections matchers are finally ported, PHP-specific
  25. aliases will probably be created due to a difference in naming
  26. conventions between Java's Arrays, Collections, Sets and Maps compared
  27. with PHP's Arrays.
  28. ---
  29. ** [Unless we consider POPO's (Plain Old PHP Objects) akin to JavaBeans]
  30. - The POPO thing is a joke. Java devs coin the term POJO's (Plain Old
  31. Java Objects).
  32. Usage
  33. -----
  34. Hamcrest matchers are easy to use as:
  35. ```php
  36. Hamcrest_MatcherAssert::assertThat('a', Hamcrest_Matchers::equalToIgnoringCase('A'));
  37. ```
  38. Alternatively, you can use the global proxy-functions:
  39. ```php
  40. $result = true;
  41. // with an identifier
  42. assertThat("result should be true", $result, equalTo(true));
  43. // without an identifier
  44. assertThat($result, equalTo(true));
  45. // evaluate a boolean expression
  46. assertThat($result === true);
  47. // with syntactic sugar is()
  48. assertThat(true, is(true));
  49. ```
  50. :warning: **NOTE:** the global proxy-functions aren't autoloaded by default, so you will need to load them first:
  51. ```php
  52. \Hamcrest\Util::registerGlobalFunctions();
  53. ```
  54. For brevity, all of the examples below use the proxy-functions.
  55. Documentation
  56. -------------
  57. A tutorial can be found on the [Hamcrest site](https://code.google.com/archive/p/hamcrest/wikis/TutorialPHP.wiki).
  58. Available Matchers
  59. ------------------
  60. * [Array](../master/README.md#array)
  61. * [Collection](../master/README.md#collection)
  62. * [Object](../master/README.md#object)
  63. * [Numbers](../master/README.md#numbers)
  64. * [Type checking](../master/README.md#type-checking)
  65. * [XML](../master/README.md#xml)
  66. ### Array
  67. * `anArray` - evaluates an array
  68. ```php
  69. assertThat([], anArray());
  70. ```
  71. * `hasItemInArray` - check if item exists in array
  72. ```php
  73. $list = range(2, 7, 2);
  74. $item = 4;
  75. assertThat($list, hasItemInArray($item));
  76. ```
  77. * `hasValue` - alias of hasItemInArray
  78. * `arrayContainingInAnyOrder` - check if array contains elements in any order
  79. ```php
  80. assertThat([2, 4, 6], arrayContainingInAnyOrder([6, 4, 2]));
  81. assertThat([2, 4, 6], arrayContainingInAnyOrder([4, 2, 6]));
  82. ```
  83. * `containsInAnyOrder` - alias of arrayContainingInAnyOrder
  84. * `arrayContaining` - An array with elements that match the given matchers in the same order.
  85. ```php
  86. assertThat([2, 4, 6], arrayContaining([2, 4, 6]));
  87. assertthat([2, 4, 6], not(arrayContaining([6, 4, 2])));
  88. ```
  89. * `contains` - check array in same order
  90. ```php
  91. assertThat([2, 4, 6], contains([2, 4, 6]));
  92. ```
  93. * `hasKeyInArray` - check if array has given key
  94. ```php
  95. assertThat(['name'=> 'foobar'], hasKeyInArray('name'));
  96. ```
  97. * `hasKey` - alias of hasKeyInArray
  98. * `hasKeyValuePair` - check if arary has given key, value pair
  99. ```php
  100. assertThat(['name'=> 'foobar'], hasKeyValuePair('name', 'foobar'));
  101. ```
  102. * `hasEntry` - same as hasKeyValuePair
  103. * `arrayWithSize` - check array has given size
  104. ```php
  105. assertthat([2, 4, 6], arrayWithSize(3));
  106. ```
  107. * `emptyArray` - check if array is emtpy
  108. ```php
  109. assertThat([], emptyArray());
  110. ```
  111. * `nonEmptyArray`
  112. ```php
  113. assertThat([1], nonEmptyArray());
  114. ```
  115. ### Collection
  116. * `emptyTraversable` - check if traversable is empty
  117. ```php
  118. $empty_it = new EmptyIterator;
  119. assertThat($empty_it, emptyTraversable());
  120. ```
  121. * `nonEmptyTraversable` - check if traversable isn't empty
  122. ```php
  123. $non_empty_it = new ArrayIterator(range(1, 10));
  124. assertThat($non_empty_it, nonEmptyTraversable());
  125. a
  126. ```
  127. * `traversableWithSize`
  128. ```php
  129. $non_empty_it = new ArrayIterator(range(1, 10));
  130. assertThat($non_empty_it, traversableWithSize(count(range(1, 10))));
  131. `
  132. ```
  133. ### Core
  134. * `allOf` - Evaluates to true only if ALL of the passed in matchers evaluate to true.
  135. ```php
  136. assertThat([2,4,6], allOf(hasValue(2), arrayWithSize(3)));
  137. ```
  138. * `anyOf` - Evaluates to true if ANY of the passed in matchers evaluate to true.
  139. ```php
  140. assertThat([2, 4, 6], anyOf(hasValue(8), hasValue(2)));
  141. ```
  142. * `noneOf` - Evaluates to false if ANY of the passed in matchers evaluate to true.
  143. ```php
  144. assertThat([2, 4, 6], noneOf(hasValue(1), hasValue(3)));
  145. ```
  146. * `both` + `andAlso` - This is useful for fluently combining matchers that must both pass.
  147. ```php
  148. assertThat([2, 4, 6], both(hasValue(2))->andAlso(hasValue(4)));
  149. ```
  150. * `either` + `orElse` - This is useful for fluently combining matchers where either may pass,
  151. ```php
  152. assertThat([2, 4, 6], either(hasValue(2))->orElse(hasValue(4)));
  153. ```
  154. * `describedAs` - Wraps an existing matcher and overrides the description when it fails.
  155. ```php
  156. $expected = "Dog";
  157. $found = null;
  158. // this assertion would result error message as Expected: is not null but: was null
  159. //assertThat("Expected {$expected}, got {$found}", $found, is(notNullValue()));
  160. // and this assertion would result error message as Expected: Dog but: was null
  161. //assertThat($found, describedAs($expected, notNullValue()));
  162. ```
  163. * `everyItem` - A matcher to apply to every element in an array.
  164. ```php
  165. assertThat([2, 4, 6], everyItem(notNullValue()));
  166. ```
  167. * `hasItem` - check array has given item, it can take a matcher argument
  168. ```php
  169. assertThat([2, 4, 6], hasItem(equalTo(2)));
  170. ```
  171. * `hasItems` - check array has givem items, it can take multiple matcher as arguments
  172. ```php
  173. assertThat([1, 3, 5], hasItems(equalTo(1), equalTo(3)));
  174. ```
  175. ### Object
  176. * `hasToString` - check `__toString` or `toString` method
  177. ```php
  178. class Foo {
  179. public $name = null;
  180. public function __toString() {
  181. return "[Foo]Instance";
  182. }
  183. }
  184. $foo = new Foo;
  185. assertThat($foo, hasToString(equalTo("[Foo]Instance")));
  186. ```
  187. * `equalTo` - compares two instances using comparison operator '=='
  188. ```php
  189. $foo = new Foo;
  190. $foo2 = new Foo;
  191. assertThat($foo, equalTo($foo2));
  192. ```
  193. * `identicalTo` - compares two instances using identity operator '==='
  194. ```php
  195. assertThat($foo, is(not(identicalTo($foo2))));
  196. ```
  197. * `anInstanceOf` - check instance is an instance|sub-class of given class
  198. ```php
  199. assertThat($foo, anInstanceOf(Foo::class));
  200. ```
  201. * `any` - alias of `anInstanceOf`
  202. * `nullValue` check null
  203. ```php
  204. assertThat(null, is(nullValue()));
  205. ```
  206. * `notNullValue` check not null
  207. ```php
  208. assertThat("", notNullValue());
  209. ```
  210. * `sameInstance` - check for same instance
  211. ```php
  212. assertThat($foo, is(not(sameInstance($foo2))));
  213. assertThat($foo, is(sameInstance($foo)));
  214. ```
  215. * `typeOf`- check type
  216. ```php
  217. assertThat(1, typeOf("integer"));
  218. ```
  219. * `notSet` - check if instance property is not set
  220. ```php
  221. assertThat($foo, notSet("name"));
  222. ```
  223. * `set` - check if instance property is set
  224. ```php
  225. $foo->name = "bar";
  226. assertThat($foo, set("name"));
  227. ```
  228. ### Numbers
  229. * `closeTo` - check value close to a range
  230. ```php
  231. assertThat(3, closeTo(3, 0.5));
  232. ```
  233. * `comparesEqualTo` - check with '=='
  234. ```php
  235. assertThat(2, comparesEqualTo(2));
  236. ```
  237. * `greaterThan` - check '>'
  238. ```
  239. assertThat(2, greaterThan(1));
  240. ```
  241. * `greaterThanOrEqualTo`
  242. ```php
  243. assertThat(2, greaterThanOrEqualTo(2));
  244. ```
  245. * `atLeast` - The value is >= given value
  246. ```php
  247. assertThat(3, atLeast(2));
  248. ```
  249. * `lessThan`
  250. ```php
  251. assertThat(2, lessThan(3));
  252. ```
  253. * `lessThanOrEqualTo`
  254. ```php
  255. assertThat(2, lessThanOrEqualTo(3));
  256. ```
  257. * `atMost` - The value is <= given value
  258. ```php
  259. assertThat(2, atMost(3));
  260. ```
  261. ### String
  262. * `emptyString` - check for empty string
  263. ```php
  264. assertThat("", emptyString());
  265. ```
  266. * `isEmptyOrNullString`
  267. ```php
  268. assertThat(null, isEmptyOrNullString());
  269. ```
  270. * `nullOrEmptyString`
  271. ```php
  272. assertThat("", nullOrEmptyString());
  273. ```
  274. * `isNonEmptyString`
  275. ```php
  276. assertThat("foo", isNonEmptyString());
  277. ```
  278. * `nonEmptyString`
  279. ```php
  280. assertThat("foo", nonEmptyString());
  281. ```
  282. * `equalToIgnoringCase`
  283. ```php
  284. assertThat("Foo", equalToIgnoringCase("foo"));
  285. ```
  286. * `equalToIgnoringWhiteSpace`
  287. ```php
  288. assertThat(" Foo ", equalToIgnoringWhiteSpace("Foo"));
  289. ```
  290. * `matchesPattern` - matches with regex pattern
  291. ```php
  292. assertThat("foobarbaz", matchesPattern('/(foo)(bar)(baz)/'));
  293. ```
  294. * `containsString` - check for substring
  295. ```php
  296. assertThat("foobar", containsString("foo"));
  297. ```
  298. * `containsStringIgnoringCase`
  299. ```php
  300. assertThat("fooBar", containsStringIgnoringCase("bar"));
  301. ```
  302. * `stringContainsInOrder`
  303. ```php
  304. assertThat("foo", stringContainsInOrder("foo"));
  305. ```
  306. * `endsWith` - check string that ends with given value
  307. ```php
  308. assertThat("foo", endsWith("oo"));
  309. ```
  310. * `startsWith` - check string that starts with given value
  311. ```php
  312. assertThat("bar", startsWith("ba"));
  313. ```
  314. ### Type-checking
  315. * `arrayValue` - check array type
  316. ```php
  317. assertThat([], arrayValue());
  318. ```
  319. * `booleanValue`
  320. ```php
  321. assertThat(true, booleanValue());
  322. ```
  323. * `boolValue` - alias of booleanValue
  324. * `callableValue` - check if value is callable
  325. ```php
  326. $func = function () {};
  327. assertThat($func, callableValue());
  328. ```
  329. * `doubleValue`
  330. ```php
  331. assertThat(3.14, doubleValue());
  332. ```
  333. * `floatValue`
  334. ```php
  335. assertThat(3.14, floatValue());
  336. ```
  337. * `integerValue`
  338. ```php
  339. assertThat(1, integerValue());
  340. ```
  341. * `intValue` - alias of `integerValue`
  342. * `numericValue` - check if value is numeric
  343. ```php
  344. assertThat("123", numericValue());
  345. ```
  346. * `objectValue` - check for object
  347. ```php
  348. $obj = new stdClass;
  349. assertThat($obj, objectValue());
  350. ```
  351. * `anObject`
  352. ```php
  353. assertThat($obj, anObject());
  354. ```
  355. * `resourceValue` - check resource type
  356. ```php
  357. $fp = fopen("/tmp/foo", "w+");
  358. assertThat($fp, resourceValue());
  359. ```
  360. * `scalarValue` - check for scaler value
  361. ```php
  362. assertThat(1, scalarValue());
  363. ```
  364. * `stringValue`
  365. ```php
  366. assertThat("", stringValue());
  367. ```
  368. ### XML
  369. * `hasXPath` - check xml with a xpath
  370. ```php
  371. $xml = <<<XML
  372. <books>
  373. <book>
  374. <isbn>1</isbn>
  375. </book>
  376. <book>
  377. <isbn>2</isbn>
  378. </book>
  379. </books>
  380. XML;
  381. $doc = new DOMDocument;
  382. $doc->loadXML($xml);
  383. assertThat($doc, hasXPath("book", 2));
  384. ```