<?php require_once "vendor/autoload.php"; FUnit::test("SESMessage -- create full message", function () { $message = new \Gaggle\SESMessage(); $message->setFrom("*****@*****.**"); $message->setTo(["*****@*****.**", "*****@*****.**"]); $message->setCc(["*****@*****.**"]); $message->setCc(["*****@*****.**"], true); $message->setBcc(["*****@*****.**"]); $message->setReplyTo(["*****@*****.**"]); $message->setReturnPath("*****@*****.**"); $message->setSubject("THIS IS A SUBJECT"); $message->setMessage("<strong>OMG!</strong> It's like, <b>WOAH!</b> For real, I'm kinda <i>freaking</i> out right now."); $expected = array("Source" => "*****@*****.**", "Destination" => array("ToAddresses" => ["*****@*****.**", "*****@*****.**"], "CcAddresses" => ["*****@*****.**", "*****@*****.**"], "BccAddresses" => ["*****@*****.**"]), "Message" => array("Subject" => array("Data" => "THIS IS A SUBJECT", "Charset" => "UTF-8"), "Body" => array('Html' => array("Data" => "<strong>OMG!</strong> It's like, <b>WOAH!</b> For real, I'm kinda <i>freaking</i> out right now.", "Charset" => "UTF-8"), 'Text' => array("Data" => "OMG! It's like, WOAH! For real, I'm kinda freaking out right now.", "Charset" => "UTF-8"))), "ReplyToAddresses" => ["*****@*****.**"], "ReturnPath" => "*****@*****.**"); FUnit::equal($expected, $message->marshal()); }); FUnit::test("SESMessage -- create partial message", function () { $message = new \Gaggle\SESMessage(); $message->setFrom("*****@*****.**"); $message->setTo(["*****@*****.**", "*****@*****.**"]); // $message->setCc(["*****@*****.**"]); // $message->setCc(["*****@*****.**"], true); // $message->setBcc(["*****@*****.**"]); // $message->setReplyTo(["*****@*****.**"]); // $message->setReturnPath("*****@*****.**"); $message->setSubject("THIS IS A SUBJECT"); $message->setMessage("<strong>OMG!</strong> It's like, <b>WOAH!</b> For real, I'm kinda <i>freaking</i> out right now."); $expected = array("Source" => "*****@*****.**", "Destination" => array("ToAddresses" => ["*****@*****.**", "*****@*****.**"]), "Message" => array("Subject" => array("Data" => "THIS IS A SUBJECT", "Charset" => "UTF-8"), "Body" => array('Html' => array("Data" => "<strong>OMG!</strong> It's like, <b>WOAH!</b> For real, I'm kinda <i>freaking</i> out right now.", "Charset" => "UTF-8"), 'Text' => array("Data" => "OMG! It's like, WOAH! For real, I'm kinda freaking out right now.", "Charset" => "UTF-8")))); FUnit::equal($expected, $message->marshal()); });
<?php require_once "vendor/autoload.php"; FUnit::test("PlainMessage::marshal()", function () { $message = new Gaggle\PlainMessage(); $message->setHeaders(["from" => "*****@*****.**", "to" => "*****@*****.**", "subject" => "this should be plain text"]); $message->setMessage("this is some <strong>plain</strong> text."); $expected = file_get_contents("./tests/samples/sample_PlainText.txt"); $expected = str_replace("\n", "\r\n", $expected); FUnit::equal($expected, $message->marshal()); });
<?php require_once "vendor/autoload.php"; FUnit::test("Gooseberry::get()", function () { $dingle = new \Gooseberry\Gooseberry("http://httpbin.org", ["get", "post", "headers"]); $response = $dingle->get("get", array("test_key" => "test_value")); $decoded = json_decode($response, true); FUnit::equal($decoded["args"], ["test_key" => "test_value"], "get response 'form' property"); FUnit::equal($decoded["url"], "http://httpbin.org/get?test_key=test_value", "get response 'url' property"); }); FUnit::test("Gooseberry::post()", function () { $dingle = new \Gooseberry\Gooseberry("http://httpbin.org", ["get", "post", "headers"]); $response = $dingle->post("post", array("test_key" => "test_value")); $decoded = json_decode($response, true); FUnit::equal($decoded["form"], ["test_key" => "test_value"], "post response 'form' property"); FUnit::equal($decoded["url"], "http://httpbin.org/post", "post response 'url' property"); }); FUnit::test("Gooseberry::getInfo()", function () { //wrapper_type $dingle = new \Gooseberry\Gooseberry("http://httpbin.org", ["get", "post", "headers"]); $response = $dingle->post("post", array("test_key" => "test_value")); $info = $dingle->getInfo(); FUnit::equal($info["wrapper_type"], "http"); }); FUnit::test("Gooseberry::setHeaders()", function () { $dingle = new \Gooseberry\Gooseberry("http://httpbin.org", ["get", "post", "headers"]); $dingle->setHeaders(["User-Agent" => "PHP CLI - Gooseberry"]); $response = $dingle->post("post", array("test_key" => "test_value")); $decoded = json_decode($response, true); FUnit::equal($decoded["headers"]["User-Agent"], "PHP CLI - Gooseberry"); });
require __DIR__ . '/../vendor/autoload.php'; use FUnit as fu; use Knlv\Zf2\Validator\VatNumber; fu::test('Test getValidator returns default composed validator', function () { $validator = new VatNumber(); fu::ok($validator->getValidator() instanceof Ddeboer\Vatin\Validator); }); fu::test('Test options are set', function () { $validator = new VatNumber(array('country' => 'EL', 'checkExistence' => false)); fu::equal('EL', $validator->getCountry()); fu::equal(false, $validator->getCheckExistence()); }); fu::test('Test throws exception on invalid country', function () { fu::throws(function () { $validator = new VatNumber(array('country' => 'GR')); }, array(), 'Zend\\Validator\\Exception\\InvalidArgumentException'); }); fu::test('Test validates same as composed validator', function () { $data = array(array(false, 'EL', '123456789', true), array(false, 'BE', '0123456789', true), array(true, 'NL', '987654321B01', false), array(true, 'NL', '7654321B01', false), array(true, 'BE', '01234567', false)); $validator = new VatNumber(); fu::all_ok($data, function ($values) use($validator) { $validator->setCheckExistence($values[0]); $validator->setCountry($values[1]); return $validator->isValid($values[2]) === $values[3]; }); }); fu::test('Test messages', function () { $validator = new VatNumber(); $validator->isValid("EL123456789"); fu::equal($validator->getMessages(), array('vatInvalid' => 'The VAT is invalid')); });
<?php require __DIR__ . '/../vendor/autoload.php'; use FUnit as fu; fu::test("Test config_merge with two files", function () { $config = \Knlv\config_merge(__DIR__ . '/data', array('global', 'local')); $expected = (include __DIR__ . '/data/config_out1.php'); fu::equal($config, $expected); }); fu::test("Test config_merge with three files", function () { $config = \Knlv\config_merge(__DIR__ . '/data', array('global', 'local', 'development')); $expected = (include __DIR__ . '/data/config_out2.php'); fu::equal($config, $expected); });
<?php require __DIR__ . '/../vendor/autoload.php'; use FUnit as fu; use Knlv\Zf2\Validator\ExplodeWithContext; use Zend\Validator\Callback; // Zend\Validator\Callback uses context in isValid method in order to test fu::setup(function () { $validator = new ExplodeWithContext(); fu::fixture('validator', $validator); }); fu::test('Test explode_with_context passes context', function () { $validator = fu::fixture('validator'); $validator->setValueDelimiter(','); $validator->setValidator(new Callback(function ($value, $context) { fu::equal('value', $context, 'Assert context pass'); return false; })); $validator->isValid('value 1,value 2,other value', 'value'); }); fu::test('Test explode_with_context validates correctly', function () { $validator = fu::fixture('validator'); $validator->setValueDelimiter('|'); $validator->setValidator(new Callback(function ($value, $context) { // value begins with value from context return 0 === strpos($value, $context); })); fu::ok($validator->isValid('value 1|value 2|value 3', 'value'), 'Assert returns true if validates'); fu::not_ok($validator->isValid('value 1|other value 2|value 3', 'value'), 'Assert returns false if one does not validate'); });
<?php use FUnit as fu; require_once __DIR__ . '/../src/FUnit.php'; fu::test('test output when FUnit::set_disable_reporting(true)', function () use($report_disabled) { $report_disabled = shell_exec("php " . __DIR__ . "/output_scripts/set_disable_reporting_true.php"); fu::strict_equal(0, strlen($report_disabled), "no report output"); }); fu::test('test output when FUnit::set_disable_reporting(false)', function () use($report_disabled) { $report_disabled = shell_exec("php " . __DIR__ . "/output_scripts/set_disable_reporting_false.php"); fu::strict_equal(0, strlen($report_disabled), "Report output received"); }); fu::run();
<?php require __DIR__ . '/../vendor/autoload.php'; use FUnit as fu; use Knlv\Zf2\Filter\Transelot; fu::test("Test transelot filter works", function () { $input = "αβγδεζηικλμνξοπρστυφωάίύέόήώϊϋΐΰςΑΒΓΔΕΖΗΙΚΛΜΝΞΟΠΡΣΤΥΦΩΆΊΎΈΌΉΏΪΫ"; $expected = "avgdeziiklmnxoprstyfoaiyeoioieiysAVGDEZIIKLMNXOPRSTYFOΑIYEOIOIY"; $filter = new Transelot(); fu::equal($filter->filter($input), $expected, "Assert translitteration works"); });
<?php require __DIR__ . '/../vendor/autoload.php'; use FUnit as fu; use Zend\Permissions\Rbac\Rbac; use Knlv\Zf2\Permissions\Rbac\Assertion\Callback as RbacCallback; fu::setup(function () { $rbac = new Rbac(); $rbac->addRole('member'); $rbac->addRole('guest', 'member'); $rbac->getRole('guest')->addPermission('read'); $rbac->getRole('member')->addPermission('write'); fu::fixture('rbac', $rbac); }); fu::test('Test rbac callback assertion', function () { $rbac = fu::fixture('rbac'); $test = $rbac->isGranted('guest', 'read') && $rbac->isGranted('member', 'read') && !$rbac->isGranted('guest', 'write') && $rbac->isGranted('member', 'write'); fu::ok($test, 'Test rbac without assertions'); $assertTrue = new RbacCallback(function () { return true; }); $assertFalse = new RbacCallback(function () { return false; }); fu::not_ok($rbac->isGranted('member', 'read', $assertFalse), 'Assert permission not granted when callback returns false'); fu::ok($rbac->isGranted('member', 'write', $assertTrue), 'Assert permission granted when callback returns true'); });
fu::ok($e instanceof InvalidArgumentException, 'Throws InvalidArgumentException on invalid argument'); } }); fu::test("Test memoize works", function () { $counter = 0; $function = function ($arg) use(&$counter) { return $arg . ($counter += 1); }; fu::equal('test1', $function('test'), 'Call with no memoization increments external counter'); fu::equal('test2', $function('test'), 'Call with no memoization increments external counter'); $memoized = Knlv\memoize($function); fu::equal('test3', $memoized('test'), '1st call memoized function increments external counter'); fu::equal('test3', $memoized('test'), '2nd Call memoized function returns cached value'); fu::equal(3, $counter, 'Assert counter not changed after 2nd memoized function call'); }); fu::test("Test memoize use separate cache foreach function", function () { $function1 = function ($arg) { return $arg . $arg; }; $function2 = function ($arg) { return $arg; }; fu::equal('testtest', $function1('test'), 'Assert not memoized function 1 works'); fu::equal('test', $function2('test'), 'Assert not memoized function 2 works'); $memoized1 = Knlv\memoize($function1); $memoized2 = Knlv\memoize($function2); fu::equal('testtest', $function1('test'), 'Assert memoized function 1 works 1st call'); fu::equal('testtest', $function1('test'), 'Assert memoized function 1 works 2nd call'); fu::equal('test', $function2('test'), 'Assert memoized function 2 works 1st call'); fu::equal('test', $function2('test'), 'Assert memoized function 2 works 2nd call'); });
<?php use FUnit as fu; require_once __DIR__ . '/../src/FUnit.php'; fu::suite('Fixture test suite'); fu::test('Test adding fixtures', function () { fu::fixture('a', array(1, 2, 3)); $a = fu::fixture('a'); fu::strict_equal(array(1, 2, 3), $a); }); fu::test('Test resetting fixtures', function () { fu::fixture('a', array(1, 2, 3)); $a = fu::fixture('a'); fu::reset_fixtures(); fu::ok(is_null(fu::fixture('a'))); }); fu::run();
<?php require_once "vendor/autoload.php"; FUnit::test("simple_scan_args()", function () { $input = array("filename.txt", "-f1", "-flag1", "--f2", "--flag2", "-key1=value", "-key2", "value2", "JUNK-IGNORE-ME", "--key3=value", "--key4", "value4"); $output = simple_scan_args($input, array("key1", "key2", "key3", "key4", "key5"), array("f1", "f2", "f3", "flag1", "flag2", "flag3")); $expected = array("f1" => true, "f2" => true, "f3" => false, "flag1" => true, "flag2" => true, "flag3" => false, "key1" => "value", "key2" => "value2", "key3" => "value", "key4" => "value4"); FUnit::equal($expected, $output); });
FUnit::equal($expected, ["name" => $output->getName(), "type" => $output->getType(), "size" => $output->getSize(), "tmp_name" => $output->getTmpName(), "error" => $output->getError()]); }); FUnit::test("FileMarshal::marshal() testing countable", function () { $input = array("fieldname2" => array('name' => array("field1", "field2"), 'type' => array("plain/text", "plain/text"), 'size' => array("1024", "1024"), 'tmp_name' => array("asdfqwerty1", "asdfqwerty2"), 'error' => array("0", "0"))); $files = new \FileMarshal\FileMarshal(new FileMarshal\UploadedFileFactory()); $files->marshal($input["fieldname2"]); Funit::equal(2, count($files)); }); FUnit::test("FileMarshal::marshal() testing iterator via foreach", function () { $input = array("fieldname2" => array('name' => array("field1", "field2"), 'type' => array("plain/text", "plain/text"), 'size' => array("1024", "1024"), 'tmp_name' => array("asdfqwerty1", "asdfqwerty2"), 'error' => array("0", "0"))); $files = new \FileMarshal\FileMarshal(new FileMarshal\UploadedFileFactory()); $files->marshal($input["fieldname2"]); foreach ($files as $file) { FUnit::ok(in_array($file->getName(), $input["fieldname2"]["name"])); FUnit::ok(in_array($file->getType(), $input["fieldname2"]["type"])); FUnit::ok(in_array($file->getTmpName(), $input["fieldname2"]["tmp_name"])); FUnit::ok(in_array($file->getError(), $input["fieldname2"]["error"])); FUnit::ok(in_array($file->getSize(), $input["fieldname2"]["size"])); } }); FUnit::test("UploadedFile::hasError()", function () { $input["fieldname"] = array('name' => "", 'type' => "", 'size' => "", 'tmp_name' => "", 'error' => UPLOAD_ERR_NO_FILE); $file = new \FileMarshal\FileMarshal(new FileMarshal\UploadedFileFactory()); try { $file->marshal($input["fieldname"]); } catch (\FileMarshal\Exceptions\UploadErrNoFile $e) { FUnit::ok(1); } catch (\Exception $e) { Funit::fail("Wrong exception was thrown"); } });
fu::strict_equal(false, fu::assert_has('bingo', $obj)['result'], "\$obj does not have property 'bingo'"); }); fu::test('FUnit::assert_not_has tests', function () { $arr = array("foo" => true, "bar" => null, "baz" => "bingo"); $obj = new stdClass(); $obj->foo = true; $obj->bar = null; $obj->baz = "bingo"; fu::strict_equal(false, fu::assert_not_has('foo', $arr)['result'], "\$arr has key 'foo'"); fu::strict_equal(false, fu::assert_not_has('bar', $arr)['result'], "\$arr has key 'bar'"); fu::strict_equal(false, fu::assert_not_has('baz', $arr)['result'], "\$arr has key 'baz'"); fu::strict_equal(true, fu::assert_not_has('bingo', $arr)['result'], "\$arr does not have key 'bingo'"); fu::strict_equal(false, fu::assert_not_has('foo', $obj)['result'], "\$obj has property 'foo'"); fu::strict_equal(false, fu::assert_not_has('bar', $obj)['result'], "\$obj has property 'bar'"); fu::strict_equal(false, fu::assert_not_has('baz', $obj)['result'], "\$obj has property 'baz'"); fu::strict_equal(true, fu::assert_not_has('bingo', $obj)['result'], "\$obj does not have property 'bingo'"); }); fu::test('FUnit::assert_fail tests', function () { fu::strict_equal(false, fu::assert_fail()['result'], "forced fail"); }); fu::test('FUnit::assert_expect_fail tests', function () { fu::strict_equal(false, fu::assert_expect_fail()['result'], "forced expected fail"); }); fu::test('FUnit::assert_pass tests', function () { fu::strict_equal(true, fu::assert_pass()['result'], "forced pass"); }); fu::test('Ensure not including msg param has no side effects', function () { fu::strict_equal(true, fu::assert_equal(1, 1, 'poop')['result']); fu::strict_equal(true, fu::assert_equal(1, 1)['result']); }); fu::run();
$message = new Gaggle\RichMessage(); $message->setHeaders(["from" => "*****@*****.**", "to" => "*****@*****.**", "subject" => "this should be rich text"]); $message->setMessage("this is some <strong>html</strong> text."); $expected = file_get_contents("./tests/samples/sample_RichText.txt"); $expected = str_replace("\n", "\r\n", $expected); $cleanups = ["!boundary=\"\\w+\"!i" => "boundary=\"SHA1-HASH\"", "!--\\w+!i" => "--SHA1-HASH"]; $marshaled = preg_replace(array_keys($cleanups), array_values($cleanups), $message->marshal()); FUnit::equal($expected, $marshaled); }); FUnit::test("RichMessage::marshal() w/ attachment", function () { $message = new Gaggle\RichMessage(); $message->setHeaders(["from" => "*****@*****.**", "to" => "*****@*****.**", "subject" => "this should be rich text w/ an attachment"]); $message->setMessage("this is some <strong>html</strong> text."); $message->attachFile("./tests/samples/sample_attachment.txt"); $expected = file_get_contents("./tests/samples/sample_RichTextAttachment.txt"); $expected = str_replace("\n", "\r\n", $expected); $cleanups = ["!boundary=\"\\w+\"!i" => "boundary=\"SHA1-HASH\"", "!--\\w+!i" => "--SHA1-HASH"]; $marshaled = preg_replace(array_keys($cleanups), array_values($cleanups), $message->marshal()); // drop($expected, $marshaled); FUnit::equal($expected, $marshaled, "random/unique sha1s are difficult to test against."); }); FUnit::test("RichMessage::marshal() w/ all headers", function () { $message = new Gaggle\RichMessage(); $message->setFrom("*****@*****.**")->setTo(["*****@*****.**"])->setReplyTo(["*****@*****.**"])->setCc(["*****@*****.**"])->setBcc(["*****@*****.**"])->setReturnPath("*****@*****.**")->setSubject("this should be rich text w/ all headers")->setMessage("this is some <strong>html</strong> text."); $expected = file_get_contents("./tests/samples/sample_RichTextAllHeaders.txt"); $expected = str_replace("\n", "\r\n", $expected); $cleanups = ["!boundary=\"\\w+\"!i" => "boundary=\"SHA1-HASH\"", "!--\\w+!i" => "--SHA1-HASH"]; $marshaled = preg_replace(array_keys($cleanups), array_values($cleanups), $message->marshal()); // drop($expected, $marshaled); FUnit::equal($expected, $marshaled, "random/unique sha1s are difficult to test against."); });
return false; }; $adapter = new CallbackAdapter($callback); $adapter->setIdentity('testuser'); $adapter->setCredential('testpass'); $result = $adapter->authenticate(); fu::ok($result instanceof Result, 'Assert Authentication result is instanceof Zend\\Authentication\\Result'); fu::equal(Result::SUCCESS, $result->getCode(), 'Assert success code in result on success'); fu::equal('testuser', $result->getIdentity(), 'Assert identity is returned on success'); $adapter->setCredential('someotherpass'); $result = $adapter->authenticate(); fu::equal(Result::FAILURE, $result->getCode(), 'Assert failure code in result on failure'); fu::equal(null, $result->getIdentity(), 'Assert null is returned on failure'); }); fu::test('Test authentication callback adapter without credentials', function () { $callbackSuccess = function () { return 'testuser'; }; $callbackFailure = function () { return false; }; $adapter = new CallbackAdapter($callbackSuccess); $result = $adapter->authenticate(); fu::ok($result instanceof Result, 'Assert Authentication result is instanceof Zend\\Authentication\\Result'); fu::equal(Result::SUCCESS, $result->getCode(), 'Assert success code in result on success'); fu::equal('testuser', $result->getIdentity(), 'Assert identity is returned on success'); $adapter = new CallbackAdapter($callbackFailure); $result = $adapter->authenticate(); fu::equal(Result::FAILURE, $result->getCode(), 'Assert failure code in result on failure'); fu::equal(null, $result->getIdentity(), 'Assert null is returned on failure'); });
<?php require __DIR__ . '/../vendor/autoload.php'; use FUnit as fu; use Knlv\Slim\Middleware\Callback; date_default_timezone_set('Europe/Athens'); fu::test('Test middleware throws exception on invlalid callable', function () { try { new Callback('test'); } catch (Exception $e) { fu::ok($e instanceof InvalidArgumentException, 'Throws if no callback is given'); } }); fu::test('Test middleware set callback', function () { $callback = function () { }; $middleware = new Callback($callback); $reflection = new ReflectionObject($middleware); $propertyReflection = $reflection->getProperty('callback'); $propertyReflection->setAccessible(true); fu::equal($callback, $propertyReflection->getValue($middleware), 'Callback is set'); }); fu::test('Test middleware call uses callback', function () { $middleware = new Callback(function ($m) use(&$middleware) { fu::pass('Callable is called'); fu::equal($middleware, $m, 'Passes itself as callable argument'); }); $middleware->call(); });
}; fu::throws($callback, 'RuntimeException', 'Correct exception'); $callback = function ($foo) { throw new RuntimeException($foo); }; fu::throws($callback, array('bar'), 'LogicException', 'Not the correct exception'); }); fu::test('Forced failure', function () { fu::fail('This is a forced fail'); }); fu::test('Expected failure', function () { fu::expect_fail('This is a good place to describe a missing test'); }); fu::test('Forced Errors/Exception', function () { trigger_error('This was triggered inside a test', E_USER_ERROR); trigger_error('This was triggered inside a test', E_USER_NOTICE); throw new Exception('This was thrown inside a test'); }); fu::test('Checking iterables with all_ok', function () { $ints = array(1, 2, 3, 4, 5); fu::all_ok($ints, 'is_int', "\$ints are all integers"); $ints = array(1, 2, 3, "four", 5); fu::all_ok($ints, 'is_int', "\$ints are all integers"); $evens = array('a' => 2, 'b' => 42, 'c' => 68, 'd' => 800); $evens_ao = new ArrayObject($evens); fu::all_ok($evens_ao, function ($val) { return $val % 2 === 0; }, "\$evens_ao are all even"); }); $exit = fu::run(); exit($exit);
use FUnit as fu; fu::setup(function () { // set a fixture to use in tests fu::fixture('foobar', array('foo' => 'bar')); }); fu::teardown(function () { // this resets the fu::$fixtures array. May not provide clean shutdown fu::reset_fixtures(); }); fu::test('Checking for exceptions', function () { $callback = function () { throw new RuntimeException(); }; fu::throws($callback, 'RuntimeException', 'Correct exception'); $callback = function ($foo) { throw new RuntimeException($foo); }; fu::throws($callback, array('bar'), 'LogicException', 'Not the correct exception'); }); fu::test('Forced failure', function () { fu::fail('This is a forced fail'); }); fu::test('Expected failure', function () { fu::expect_fail('This is a good place to describe a missing test'); }); fu::test('Forced Errors/Exception', function () { trigger_error('This was triggered inside a test', E_USER_ERROR); trigger_error('This was triggered inside a test', E_USER_NOTICE); throw new Exception('This was thrown inside a test'); }); fu::run();
use Zend\Permissions\Acl\Acl; use Knlv\Zf2\Permissions\Acl\Assertion\Callback as AclCallback; fu::setup(function () { $acl = new Acl(); // add roles $acl->addRole('guest'); $acl->addRole('member', 'guest'); // add resources $acl->addResource('article'); // add rules $acl->allow('guest', 'article', array('read')); $acl->allow('member', 'article', array('write', 'delete')); fu::fixture('acl', $acl); }); fu::test('Test acl callback assertion', function () { $acl = fu::fixture('acl'); $test = $acl->isAllowed('guest', 'article', 'read') && $acl->isAllowed('member', 'article', 'read') && $acl->isAllowed('member', 'article', 'write') && !$acl->isAllowed('guest', 'article', 'write'); fu::ok($test, 'Test acl without assertions'); $assertTrue = new AclCallback(function () { return true; }); $assertFalse = new AclCallback(function () { return false; }); $acl->removeAllow('member', 'article', 'write'); $acl->allow('member', 'article', 'write', $assertFalse); fu::not_ok($acl->isAllowed('member', 'article', 'write'), 'Assert not allowed when callback returns false'); $acl->removeAllow('member', 'article', 'write'); $acl->allow('member', 'article', 'write', $assertTrue); fu::ok($acl->isAllowed('member', 'article', 'write'), 'Assert allowed when callback returns true'); });
<?php require __DIR__ . '/../vendor/autoload.php'; use FUnit as fu; use Knlv\Zf2\Validator\NotIdentical; fu::setup(function () { $validator = new NotIdentical(); fu::fixture('validator', $validator); }); fu::test('Test not_identical validates correctly', function () { $validator = fu::fixture('validator'); $validator->setToken('token'); fu::not_ok($validator->isValid('value', array('token' => 'value')), 'Assert validator returns false on same'); fu::ok($validator->isValid('value', array('token' => 'other')), 'Assert validator retuns true on different'); fu::ok($validator->isValid('value'), 'Assert validator returns true if no context provided'); fu::ok($validator->isValid('value', array('other_token' => 'value')), 'Assert validator returns true if token not found in context'); $validator->setToken(null); fu::not_ok($validator->isValid('value', array('token' => 'value')), 'Assert validator return false if no token is set'); }); fu::test('Test not_identical messages', function () { $validator = fu::fixture('validator'); $validator->setToken('token'); $validator->isValid('value', array('token' => 'value')); fu::has($validator::SAME, $validator->getMessages(), 'Assert same message'); $validator->isValid('value', array('token' => 'other')); $messages = $validator->getMessages(); fu::ok(empty($messages), 'Assert empty messages if validator validates'); $validator->setToken(null); $validator->isValid('value', array('token' => 'value')); fu::has($validator::MISSING_TOKEN, $validator->getMessages(), 'Assert missing token message'); });
$data = array(array('foo' => ' bazbat ', 'bar' => ' 12345 ', 'baz' => ''), array('foo' => ' bazbar ', 'bar' => ' 12345 ', 'baz' => '')); $expected = array(array('foo' => 'bazbat', 'bar' => '12345', 'baz' => ''), array('foo' => 'bazbar', 'bar' => '12345', 'baz' => '')); $collectionFilter = fu::fixture('collectionFilter'); $collectionFilter->setData($data); $collectionFilter->setUniqueFields(array('foo')); fu::ok($collectionFilter->isValid(), 'Assert inputfilter is valid'); $messages = $collectionFilter->getMessages(); fu::ok(empty($messages), 'Assert inputfilter has no error messages'); fu::equal($expected, $collectionFilter->getValues(), 'Assert inputfilter returns expected values'); $collectionFilter->setUniqueFields(array('bar')); fu::not_ok($collectionFilter->isValid(), 'Assert inputfilter is invalid'); $messages = $collectionFilter->getMessages(); fu::ok(isset($messages[1]['bar'][$collectionFilter::NOT_UNIQUE]), 'Assert message for not unique isset'); fu::equal($expected, $collectionFilter->getValues(), 'Assert inputfilter returns expected values'); }); fu::test('Test inputfilter validate for unique values in fields on invalid data', function () { $data = array(array('foo' => ' bazbatfoo ', 'bar' => ' 12345 ', 'baz' => ''), array('foo' => ' bazbatfoo ', 'bar' => ' 54321 ', 'baz' => '')); $expected = array(array('foo' => 'bazbatfoo', 'bar' => '12345', 'baz' => ''), array('foo' => 'bazbatfoo', 'bar' => '54321', 'baz' => '')); $collectionFilter = fu::fixture('collectionFilter'); $collectionFilter->setData($data); $collectionFilter->setUniqueFields(array('bar')); fu::not_ok($collectionFilter->isValid(), 'Assert inputfilter is invalid'); $messages = $collectionFilter->getMessages(); fu::ok(isset($messages[0]['foo'][Validator\StringLength::TOO_LONG]), 'Assert correct error messages'); fu::equal($expected, $collectionFilter->getValues(), 'Assert inputfilter returns expected values'); $collectionFilter->setUniqueFields(array('foo')); fu::not_ok($collectionFilter->isValid(), 'Assert inputfilter is invalid'); $messages = $collectionFilter->getMessages(); fu::ok(isset($messages[0]['foo'][Validator\StringLength::TOO_LONG]) && isset($messages[1]['foo'][Validator\StringLength::TOO_LONG]) && isset($messages[1]['foo'][$collectionFilter::NOT_UNIQUE]), 'Assert message for not unique isset along with other'); fu::equal($expected, $collectionFilter->getValues(), 'Assert inputfilter returns expected values'); });
$hydrator = new ObjectProperty(); $strategy = new DateTimeStrategy(); $hydrator->addStrategy('created', $strategy); fu::fixture('strategy', $strategy); fu::fixture('hydrator', $hydrator); }); fu::test('Testing hydrate/extract methods', function () { $hydrator = fu::fixture('hydrator'); $object = new stdClass(); $object->name = 'test'; $object->data = array('data1', 'data2'); $object->created = new DateTime('2015-01-02 10:10:10'); $expected = array('name' => 'test', 'data' => array('data1', 'data2'), 'created' => '2015-01-02 10:10:10'); fu::equal($expected, $hydrator->extract($object), 'Assert extract works'); fu::equal($object, $hydrator->hydrate($expected, new stdClass()), 'Assert hydrate works'); }); fu::test('Test set/get format methods', function () { $strategy = fu::fixture('strategy'); fu::equal($strategy::DEFAULT_FORMAT, $strategy->getFormat(), 'Assert default format if no other set'); $strategy->setFormat(DateTime::ATOM); fu::equal(DateTime::ATOM, $strategy->getFormat(), 'Assert format changed'); }); fu::test('Test set/get timzone methods', function () { $strategy = fu::fixture('strategy'); fu::equal(new DateTimeZone(date_default_timezone_get()), $strategy->getTimezone(), 'Assert default timezone if no other set'); $timezone = new DateTimeZone('Europe/London'); $strategy->setTimezone($timezone); fu::equal($timezone, $strategy->getTimezone(), 'Assert timezone set as object'); $strategy->setTimezone('Europe/Athens'); fu::equal($timezone, $strategy->getTimezone(), 'Assert timezone set as string'); });
fu::strict_equal('Fixture Suite', $ts->getName()); }); fu::test("Check suite run state", function () { $ts = fu::fixture('ts'); fu::strict_equal(false, $ts->run); $ts->run(); fu::strict_equal(true, $ts->run); }); fu::test("Check suite exit code 1", function () { $ts = fu::fixture('ts'); fu::strict_equal(0, $ts->getExitCode()); $ts->addTest('known to fail for suite', function () use($ts) { // this forces the result of this assertion to be recorded in // the `$ts` TestSuite instance fu::fail($ts, 'this always fails'); }); $ts->run(); fu::strict_equal(1, $ts->getExitCode()); }); fu::test("Check suite exit code 0", function () { $ts = fu::fixture('ts'); fu::strict_equal(0, $ts->getExitCode()); $ts->addTest('known to fail for suite', function () use($ts) { // this forces the result of this assertion to be recorded in // the `$ts` TestSuite instance fu::pass($ts, 'this always fails'); }); $ts->run(); fu::strict_equal(0, $ts->getExitCode()); }); fu::run();
<?php /** * you should run this standalone (not with the test runner) */ use FUnit as fu; use FUnit\TestSuite; require_once __DIR__ . '/../../src/FUnit.php'; fu::test('FUnit::set_disable_reporting(true)', function () { fu::set_disable_reporting(true); fu::equal(true, fu::$disable_reporting, "\$disable_reporting is true"); }); fu::set_silence(true); fu::set_disable_reporting(false); fu::run();
<?php use FUnit as fu; fu::setup(function () { // set a fixture to use in tests fu::fixture('foobar', array('foo' => 'bar')); }); fu::teardown(function () { // this resets the fu::$fixtures array. May not provide clean shutdown fu::reset_fixtures(); }); fu::test("test for PHP 5.3 or above", function () { fu::strict_equal(true, version_compare(PHP_VERSION, '5.3.0') >= 0, "current PHP is >= 5.3.0"); }); fu::run();
<?php require __DIR__ . '/../vendor/autoload.php'; use FUnit as fu; use Zend\Stdlib\Hydrator\ObjectProperty; use Knlv\Zf2\Hydrator\Strategy\MultilineTextStrategy; fu::setup(function () { $hydrator = new ObjectProperty(); $strategy = new MultilineTextStrategy(); $hydrator->addStrategy('items', $strategy); fu::fixture('strategy', $strategy); fu::fixture('hydrator', $hydrator); }); fu::test('Testing hydrate/extract methods', function () { $hydrator = fu::fixture('hydrator'); $object = new stdClass(); $object->name = 'test'; $object->items = array('item1', 'item2', 'item3', 'item4', 'item5'); $expected = array('name' => 'test', 'items' => <<<EOL item1 item2 item3 item4 item5 EOL ); fu::equal($expected, $hydrator->extract($object), 'Assert extract works'); fu::equal($object, $hydrator->hydrate($expected, new stdClass()), 'Assert hydrate works'); });
<?php use FUnit as fu; fu::setup(function () { // set a fixture to use in tests fu::fixture('foobar', array('foo' => 'bar')); }); fu::teardown(function () { // this resets the fu::$fixtures array. May not provide clean shutdown fu::reset_fixtures(); }); fu::test("this is a test", function () { fu::ok(1, "the integer '1' is okay"); fu::ok(0, "the integer '0' is not okay"); // this will fail! }); fu::test("another test", function () { fu::equal(true, 1, "the integer '1' is truthy"); fu::not_strict_equal(true, 1, "the integer '1' is NOT true"); // access a fixture $foobar = fu::fixture('foobar'); fu::equal($foobar['foo'], 'bar', "the fixture 'foobar' should have a key 'foo' equal to 'baz'"); $fooarr = array('blam' => 'blaz'); fu::has('blam', $fooarr, "\$fooarr has a key named 'blam'"); $fooobj = new \StdClass(); $fooobj->blam = 'blaz'; fu::has('blam', $fooobj, "\$fooobj has a property named 'blam'"); }); fu::run();