Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Added pecs\watched() and to_have_been_called expectation

  • Loading branch information...
commit afb1fb58f21be2d5cdfe9348827b964b600e3d8b 1 parent 0ebeea4
@noonat authored
Showing with 67 additions and 1 deletion.
  1. +45 −0 lib/pecs.php
  2. +22 −1 tests/pecs/expectation.php
View
45 lib/pecs.php
@@ -44,6 +44,30 @@ function runner($newRunner=null) {
return $runner;
}
+function watched($func) {
+ if (!is_callable($func)) {
+ throw new \Exception('pecs\watched() must be passed a function');
+ }
+ return new Watched($func);
+}
+
+/// Wraps around a function and tracks when it is called.
+class Watched {
+ public $invokeArgs = array();
+ public $invokeCount = 0;
+
+ function __construct($func) {
+ $this->func = $func;
+ }
+
+ function __invoke() {
+ $args = func_get_args();
+ $this->invokeCount += 1;
+ $this->invokeArgs[] = $args;
+ return call_user_func_array($this->func, $args);
+ }
+}
+
/// Keeps track of things and does the heavy lifting.
class Runner {
function __construct() {
@@ -400,6 +424,27 @@ function throw_error($className=null, $message=null) {
return true;
}
}
+
+ function have_been_called($expected=null) {
+ if (!($this->actual instanceof Watched)) {
+ $actualClassName = get_class($e);
+ return array(
+ false,
+ "have_been_called() can only be used with pecs\watched()");
+ }
+ $actual = $this->actual->invokeCount;
+ if (is_null($expected)) {
+ return array(
+ $actual > 0,
+ "expected function to have been called, but was not");
+ } else {
+ return array(
+ $expected === $actual,
+ "expected function to have been called %d times, " .
+ "but was called %d times",
+ $expected, $actual);
+ }
+ }
}
class Failure extends \Exception {
View
23 tests/pecs/expectation.php
@@ -57,7 +57,7 @@
expect(function() { throw new InvalidArgumentException('FAIL!'); })
->to_throw('InvalidArgumentException', 'FAIL!');
});
-
+
it("should fail incorrect expectations", function() {
$expects = array(
// all of these should fail
@@ -157,5 +157,26 @@ function($s) {
expect($spec->failures[0]->getMessage())->to_be($message);
}
});
+
+ it("should allow pecs\watched() to observe a function", function() {
+ $watched = pecs\watched(function($foo, $bar) {
+ expect($foo)->to_be(1);
+ expect($bar)->to_be(2);
+ return $foo + $bar;
+ });
+ expect($watched)->not_to_have_been_called();
+ expect($watched(1, 2))->to_be(3);
+ expect($watched)->to_have_been_called();
+ expect($watched)->to_have_been_called(1);
+ expect($watched(1, 2))->to_be(3);
+ expect($watched)->to_have_been_called();
+ expect($watched)->to_have_been_called(2);
+ });
+
+ it("should fail if pecs\watched() is passed a non-callable", function() {
+ expect(function() {
+ pecs\watched(1);
+ })->to_throw('Exception', 'pecs\\watched() must be passed a function');
+ });
});
});
Please sign in to comment.
Something went wrong with that request. Please try again.