protected function getEntityManager() { if (self::$em === null) { self::$em = Environment::getService('entity_manager'); } return self::$em; }
protected function setUp() { if (!class_exists('MongoDB')) { $this->markTestSkipped('MongoDB extension not available'); } if (!self::$hasConnection) { $this->markTestSkipped('MongoDB connection not available'); } parent::setUp(); try { $this->mongodb = Environment::getService('connector')->getConnection(3); } catch (MongoConnectionException $e) { self::$hasConnection = false; $this->markTestSkipped('MongoDB connection not available'); } $this->collection = $this->mongodb->createCollection('app_news'); $table = $this->getDataSet()->getTable('app_news'); $columns = $table->getTableMetaData()->getColumns(); for ($i = 0; $i < $table->getRowCount(); $i++) { $row = array(); foreach ($columns as $name) { $row[$name] = $table->getValue($i, $name); } $this->collection->insert($row); } }
protected function getAuthorizationCode($code, $state) { $testCase = $this->testCase; $http = new Http(new Callback(function (RequestInterface $request) use($testCase) { // api request if ($request->getUri()->getPath() == '/api') { $testCase->assertEquals('Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW', (string) $request->getHeader('Authorization')); $testCase->assertEquals('application/x-www-form-urlencoded', (string) $request->getHeader('Content-Type')); $response = <<<TEXT HTTP/1.1 200 OK Content-Type: application/json;charset=UTF-8 Cache-Control: no-store Pragma: no-cache { "access_token":"2YotnFZFEjr1zCsicMWpAA", "token_type":"example", "expires_in":3600, "refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA", "example_parameter":"example_value" } TEXT; } else { throw new \RuntimeException('Invalid path'); } return ResponseParser::convert($response, ResponseParser::MODE_LOOSE)->toString(); })); $oauth = new AuthorizationCode($http, new Url('http://127.0.0.1/api'), Environment::getService('importer')); $oauth->setClientPassword(ClientCredentialsTest::CLIENT_ID, ClientCredentialsTest::CLIENT_SECRET); return $oauth; }
public function testRequest() { $testCase = $this; $http = new Http(new Callback(function (RequestInterface $request) use($testCase) { // api request if ($request->getUri()->getPath() == '/api') { $testCase->assertEquals('Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW', (string) $request->getHeader('Authorization')); $testCase->assertEquals('application/x-www-form-urlencoded', (string) $request->getHeader('Content-Type')); $testCase->assertEquals('grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA', (string) $request->getBody()); $response = <<<TEXT HTTP/1.1 200 OK Content-Type: application/json;charset=UTF-8 Cache-Control: no-store Pragma: no-cache { "access_token":"2YotnFZFEjr1zCsicMWpAA", "token_type":"example", "expires_in":3600, "example_parameter":"example_value" } TEXT; } else { throw new \RuntimeException('Invalid path'); } return ResponseParser::convert($response, ResponseParser::MODE_LOOSE)->toString(); })); $oauth = new AuthorizationCode($http, new Url('http://127.0.0.1/api'), Environment::getService('importer')); $oauth->setClientPassword(self::CLIENT_ID, self::CLIENT_SECRET); $accessToken = $oauth->getAccessToken('SplxlOBeZQQYbYS6WxSbIA'); $this->assertEquals('2YotnFZFEjr1zCsicMWpAA', $accessToken->getAccessToken()); $this->assertEquals('example', $accessToken->getTokenType()); $this->assertEquals(3600, $accessToken->getExpiresIn()); }
public function testGetForm() { $action = new Pipe(); $builder = new Builder(); $factory = Environment::getService('form_element_factory'); $action->configure($builder, $factory); $this->assertInstanceOf('Fusio\\Impl\\Form\\Container', $builder->getForm()); }
protected function doGet(Version $version) { $this->testCase->assertEquals(12, $this->queryParameters->getProperty('startIndex')); $this->testCase->assertEmpty($this->queryParameters->getProperty('bar')); $this->testCase->assertEquals(8, $this->pathParameters->getProperty('fooId')); $this->testCase->assertEmpty($this->pathParameters->getProperty('bar')); return array('entry' => Environment::getService('table_manager')->getTable('PSX\\Sql\\TestTable')->getAll()); }
protected function setUp() { parent::setUp(); if (!Environment::hasConnection()) { $this->markTestSkipped('Database connection not available'); } $this->connection = Environment::getService('connection'); }
public function testFilter() { $table = Environment::getService('table_manager')->getTable('PSX\\Sql\\TestTable'); $filter = new PrimaryKey($table); $this->assertEquals(true, $filter->apply(1)); $this->assertEquals(false, $filter->apply(32)); // test error message $this->assertEquals('%s does not exist in table', $filter->getErrorMessage()); }
protected function getResource() { $request = $this->getMock('PSX\\Http\\RequestInterface'); $response = $this->getMock('PSX\\Http\\ResponseInterface'); $context = new Context(); $context->set(Context::KEY_PATH, '/foo/bar'); $documentation = Environment::getService('controller_factory')->getController('PSX\\Controller\\Foo\\Application\\SchemaApi\\VersionViewController', $request, $response, $context)->getDocumentation(); return $documentation->getResource($documentation->getLatestVersion()); }
/** * @expectedException \ReflectionException */ public function testClassNotExist() { $context = new Context(); $context->set(Context::KEY_SOURCE, 'Foo::bar'); $request = new Request(new Url('http://127.0.0.1'), 'GET'); $response = new Response(); $simple = new DependencyInjector(Environment::getService('controller_factory')); $simple->resolve($request, $response, $context); }
public function testCommand() { $command = Environment::getService('console')->find('container'); $commandTester = new CommandTester($command); $commandTester->execute(array()); $serviceIds = Environment::getContainer()->getServiceIds(); $response = $commandTester->getDisplay(); foreach ($serviceIds as $serviceId) { $this->assertTrue(strpos($response, $serviceId) !== false, $serviceId); } }
public function getConnection() { if (!Environment::hasConnection()) { $this->markTestSkipped('No database connection available'); } if (self::$con === null) { self::$con = Environment::getService('connection'); } if ($this->connection === null) { $this->connection = self::$con; } return $this->createDefaultDBConnection($this->connection->getWrappedConnection(), Environment::getService('config')->get('psx_sql_db')); }
public function testTransform() { $template = new Twig(Environment::getService('config')); $template->setDir('tests/PSX/Template/twig'); $template->set('foo.twig.html'); $this->assertTrue($template->hasFile()); $this->assertTrue($template->isFileAvailable()); $this->assertFalse($template->isAbsoluteFile()); $this->assertEquals('foo.twig.html', $template->get()); $template->assign('foo', 'bar'); $content = $template->transform(); $this->assertEquals('Hello bar', $content); }
public function testSerializeVersionedGreater() { $author = new Serializer\TestAuthor(); $author->setName('bar'); $object = new Serializer\TestObjectVersioned(); $object->setTitle('foo'); $object->setAuthor($author); $return = Environment::getService('serializer')->serialize($object, new Version(2)); $expect = array(); $expect['title'] = 'foo'; $expect['author'] = array(); $expect['author']['name'] = 'bar'; $this->assertEquals($expect, $return); }
public function testExplicitTemplate() { $response = $this->sendRequest('http://127.0.0.1/view/explicit', 'GET', ['Accept' => 'text/html']); $data = simplexml_load_string((string) $response->getBody()); $render = (double) $data->render; $config = Environment::getService('config'); $base = (string) parse_url($config['psx_url'], PHP_URL_PATH); $this->assertEquals('bar', $data->foo); $this->assertTrue(!empty($data->self)); $this->assertEquals($config['psx_url'] . '/' . $config['psx_dispatch'], $data->url); $this->assertEquals($base, $data->base); $this->assertTrue($render > 0); $this->assertEquals('tests/PSX/Controller/Foo/Resource', $data->location); }
public function testCommand() { $command = Environment::getService('console')->find('route'); $commandTester = new CommandTester($command); $commandTester->execute(array()); $collection = Environment::getService('routing_parser')->getCollection(); $response = $commandTester->getDisplay(); foreach ($collection as $route) { $methods = implode('|', $route[0]); $this->assertTrue(strpos($response, $methods) !== false, $methods); $this->assertTrue(strpos($response, $route[1]) !== false, $route[1]); $this->assertTrue(strpos($response, $route[2]) !== false, $route[2]); } }
public function testError() { Environment::getService('config')->set('psx_debug', false); $response = $this->sendRequest('http://127.0.0.1/error', 'GET', ['Accept', 'application/json']); $body = (string) $response->getBody(); $expect = <<<XML <error> <success>false</success> <title>Internal Server Error</title> <message>The server encountered an internal error and was unable to complete your request.</message> </error> XML; $this->assertEquals(500, $response->getStatusCode(), $body); $this->assertXmlStringEqualsXmlString($expect, $body, $body); }
public function testRouteException() { $testCase = $this; $exceptionListener = $this->getMock('PSX\\Dispatch\\TestListener', array('on')); $exceptionListener->expects($this->once())->method('on')->with($this->callback(function (ExceptionThrownEvent $event) use($testCase) { $testCase->assertInstanceOf('PSX\\Event\\ExceptionThrownEvent', $event); $testCase->assertInstanceOf('PSX\\Event\\Context\\ControllerContext', $event->getContext()); $testCase->assertInstanceOf('PSX\\Http\\RequestInterface', $event->getContext()->getRequest()); $testCase->assertInstanceOf('PSX\\Http\\ResponseInterface', $event->getContext()->getResponse()); return true; })); Environment::getService('event_dispatcher')->addListener(Event::EXCEPTION_THROWN, array($exceptionListener, 'on')); $response = $this->sendRequest('http://localhost.com/exception', 'GET'); $this->assertEquals(500, $response->getStatusCode()); }
public function testExecute() { $memory = new Output\Memory(); $output = new Output\Composite(array($memory, new Output\Logger(Environment::getService('logger')))); Environment::getContainer()->set('command_output', $output); $response = $this->sendRequest('http://127.0.0.1/command?command=' . urlencode('PSX\\Command\\Foo\\Command\\FooCommand'), 'POST', ['Content-Type' => 'application/json', 'Accept' => 'application/json'], '{"foo": "bar"}'); $data = Json::decode((string) $response->getBody()); $messages = $memory->getMessages(); $this->assertArrayHasKey('output', $data); $this->assertEquals(2, count($messages)); $lines = explode("\n", trim($data['output'])); foreach ($lines as $key => $line) { $this->assertArrayHasKey($key, $messages); $this->assertContains(trim($messages[$key]), $line); } }
/** * As default we use the json reader so even if we have no content type * this should work */ public function testUnknownContentType() { $body = <<<JSON { \t"id": "1", \t"title": "foo", \t"date": "2014-07-29T23:37:00" } JSON; $request = new Message(array('Content-Type' => ''), $body); $record = Environment::getService('importer')->import(new JsonRecord(), $request); $this->assertEquals(1, $record->getId()); $this->assertEquals('foo', $record->getTitle()); $this->assertInstanceOf('DateTime', $record->getDate()); $this->assertEquals('Tue, 29 Jul 2014 23:37:00 +0000', $record->getDate()->format('r')); }
/** * Checks whether the records can be serialzed to the content format and the * content format can be serialized to the record without loosing data * * @param \PSX\Data\RecordInterface $record * @param string $content */ protected function assertRecordEqualsContent(RecordInterface $record, $content) { // serialize the record $response = $this->getWriterResponse($record); // check whether the response is the same as the content $this->assertJsonStringEqualsJsonString($content, $response); // create a new record of the same class and import the content $message = new Message(array(), $content); $class = get_class($record); $newRecord = Environment::getService('importer')->import(new $class(), $message); // get response $newResponse = $this->getWriterResponse($newRecord); // check whether the newResponse is the same as the content $this->assertJsonStringEqualsJsonString($content, $newResponse); // check whether the newResponse is the same as the response $this->assertJsonStringEqualsJsonString($response, $newResponse); }
public function testGetDocumentation() { /** @var \PSX\Api\DocumentationInterface $documentation */ $documentation = Environment::getService('resource_listing')->getDocumentation('/foo'); $this->assertInstanceOf('PSX\\Api\\DocumentationInterface', $documentation); $resource = $documentation->getResource($documentation->getLatestVersion()); $this->assertInstanceOf('PSX\\Api\\Resource', $resource); $this->assertEquals(['GET', 'POST', 'PUT', 'DELETE'], $resource->getAllowedMethods()); $this->assertEmpty($resource->getMethod('GET')->getRequest()); $this->assertInstanceOf('PSX\\Data\\SchemaInterface', $resource->getMethod('GET')->getResponse(200)); $this->assertInstanceOf('PSX\\Data\\SchemaInterface', $resource->getMethod('POST')->getRequest()); $this->assertInstanceOf('PSX\\Data\\SchemaInterface', $resource->getMethod('POST')->getResponse(200)); $this->assertInstanceOf('PSX\\Data\\SchemaInterface', $resource->getMethod('PUT')->getRequest()); $this->assertInstanceOf('PSX\\Data\\SchemaInterface', $resource->getMethod('PUT')->getResponse(200)); $this->assertInstanceOf('PSX\\Data\\SchemaInterface', $resource->getMethod('DELETE')->getRequest()); $this->assertInstanceOf('PSX\\Data\\SchemaInterface', $resource->getMethod('DELETE')->getResponse(200)); }
public function testJson() { $body = <<<XML <?xml version="1.0" encoding="UTF-8"?> <record> \t<id>1</id> \t<title>foo</title> \t<date>2014-07-29T23:37:00</date> </record> XML; $request = new Message(array('Content-Type' => 'application/xml'), $body); $record = Environment::getService('importer')->import(new XmlRecord(), $request); $this->assertEquals(1, $record->getId()); $this->assertEquals('foo', $record->getTitle()); $this->assertInstanceOf('DateTime', $record->getDate()); $this->assertEquals('Tue, 29 Jul 2014 23:37:00 +0000', $record->getDate()->format('r')); }
public function testCommand() { $stream = fopen('php://memory', 'r+'); fwrite($stream, 'GET /api HTTP/1.1' . "\n" . 'Accept: application/xml' . "\n" . ""); rewind($stream); $command = Environment::getService('console')->find('serve'); $command->setReader(new Reader\Stdin($stream)); $commandTester = new CommandTester($command); $commandTester->execute(array()); $expect = <<<XML <?xml version="1.0" encoding="UTF-8"?> <foo> <bar>foo</bar> </foo> XML; $this->assertXmlStringEqualsXmlString($expect, Environment::getService('dispatch_sender')->getResponse()); }
public function testSerialize() { /** @var \PSX\Sql\TestTableCommand $table */ $table = Environment::getService('table_manager')->getTable('PSX\\Sql\\TestTableCommand'); $row = $table->get(1); $this->assertInternalType('string', $row->getCol_bigint()); $this->assertEquals('68719476735', $row->getCol_bigint()); $this->assertInternalType('resource', $row->getCol_blob()); $this->assertEquals('foobar', stream_get_contents($row->getCol_blob())); $this->assertInternalType('boolean', $row->getCol_boolean()); $this->assertEquals(true, $row->getCol_boolean()); $this->assertInstanceOf('DateTime', $row->getCol_datetime()); $this->assertEquals('2015-01-21 23:59:59', $row->getCol_datetime()->format('Y-m-d H:i:s')); $this->assertEquals('UTC', $row->getCol_datetime()->getTimezone()->getName()); $this->assertInstanceOf('DateTime', $row->getCol_datetimetz()); $this->assertEquals('2015-01-21 23:59:59', $row->getCol_datetimetz()->format('Y-m-d H:i:s')); // mysql does not support timezones //$this->assertEquals('+01:00', $row->getCol_datetimetz())>getTimezone()->getName()); $this->assertInstanceOf('DateTime', $row->getCol_date()); $this->assertEquals('2015-01-21', $row->getCol_date()->format('Y-m-d')); $this->assertInternalType('string', $row->getCol_decimal()); $this->assertEquals('10', $row->getCol_decimal()); $this->assertInternalType('float', $row->getCol_float()); $this->assertEquals(10.37, $row->getCol_float()); $this->assertInternalType('integer', $row->getCol_integer()); $this->assertEquals(2147483647, $row->getCol_integer()); $this->assertInternalType('integer', $row->getCol_smallint()); $this->assertEquals(255, $row->getCol_smallint()); $this->assertInternalType('string', $row->getCol_text()); $this->assertEquals('foobar', $row->getCol_text()); $this->assertInstanceOf('DateTime', $row->getCol_time()); $this->assertEquals('23:59:59', $row->getCol_time()->format('H:i:s')); $this->assertInternalType('string', $row->getCol_string()); $this->assertEquals('foobar', $row->getCol_string()); $array = array('foo' => 'bar'); $object = new \stdClass(); $object->foo = 'bar'; $this->assertInternalType('array', $row->getCol_array()); $this->assertEquals($array, $row->getCol_array()); $this->assertInstanceOf('stdClass', $row->getCol_object()); $this->assertEquals($object, $row->getCol_object()); }
public function testPost() { $response = $this->sendRequest('http://127.0.0.1/backend/connection', 'POST', array('User-Agent' => 'Fusio TestCase', 'Authorization' => 'Bearer da250526d583edabca8ac2f99e37ee39aa02a3c076c0edc6929095e20ca18dcf'), json_encode(['name' => 'Foo', 'class' => 'Fusio\\Connection\\DBAL', 'config' => ['type' => 'pdo_mysql', 'host' => '127.0.0.1', 'username' => 'root', 'password' => 'foo', 'database' => 'bar']])); $body = (string) $response->getBody(); $expect = <<<'JSON' { "success": true, "message": "Connection successful created" } JSON; $this->assertEquals(201, $response->getStatusCode(), $body); $this->assertJsonStringEqualsJsonString($expect, $body, $body); // check database $sql = Environment::getService('connection')->createQueryBuilder()->select('id', 'name', 'class', 'config')->from('fusio_connection')->orderBy('id', 'DESC')->setFirstResult(0)->setMaxResults(1)->getSQL(); $row = Environment::getService('connection')->fetchAssoc($sql); $this->assertEquals(3, $row['id']); $this->assertEquals('Foo', $row['name']); $this->assertEquals('Fusio\\Connection\\DBAL', $row['class']); $this->assertEquals('a:5:{s:4:"type";s:9:"pdo_mysql";s:4:"host";s:9:"127.0.0.1";s:8:"username";s:4:"root";s:8:"password";s:3:"foo";s:8:"database";s:3:"bar";}', $row['config']); }
public function testPost() { $response = $this->sendRequest('http://127.0.0.1/backend/action', 'POST', array('User-Agent' => 'Fusio TestCase', 'Authorization' => 'Bearer da250526d583edabca8ac2f99e37ee39aa02a3c076c0edc6929095e20ca18dcf'), json_encode(['name' => 'Foo', 'class' => 'Fusio\\Action\\SqlFetchRow', 'config' => ['connection' => '1', 'sql' => 'SELECT * FROM foo']])); $body = (string) $response->getBody(); $expect = <<<'JSON' { "success": true, "message": "Action successful created" } JSON; $this->assertEquals(201, $response->getStatusCode(), $body); $this->assertJsonStringEqualsJsonString($expect, $body, $body); // check database $sql = Environment::getService('connection')->createQueryBuilder()->select('id', 'name', 'class', 'config')->from('fusio_action')->orderBy('id', 'DESC')->setFirstResult(0)->setMaxResults(1)->getSQL(); $row = Environment::getService('connection')->fetchAssoc($sql); $this->assertEquals(4, $row['id']); $this->assertEquals('Foo', $row['name']); $this->assertEquals('Fusio\\Action\\SqlFetchRow', $row['class']); $this->assertEquals('a:2:{s:10:"connection";s:1:"1";s:3:"sql";s:17:"SELECT * FROM foo";}', $row['config']); }
public function testPost() { $response = $this->sendRequest('http://127.0.0.1/backend/routes', 'POST', array('User-Agent' => 'Fusio TestCase', 'Authorization' => 'Bearer da250526d583edabca8ac2f99e37ee39aa02a3c076c0edc6929095e20ca18dcf'), json_encode(['methods' => 'GET|POST|PUT|DELETE', 'path' => '/bar', 'config' => [['status' => 4, 'name' => '1', 'methods' => [['name' => 'GET'], ['name' => 'POST'], ['name' => 'PUT'], ['name' => 'DELETE']]]]])); $body = (string) $response->getBody(); $expect = <<<'JSON' { "success": true, "message": "Route successful created" } JSON; $this->assertEquals(201, $response->getStatusCode(), $body); $this->assertJsonStringEqualsJsonString($expect, $body, $body); // check database $sql = Environment::getService('connection')->createQueryBuilder()->select('id', 'status', 'methods', 'path', 'controller', 'config')->from('fusio_routes')->orderBy('id', 'DESC')->setFirstResult(0)->setMaxResults(1)->getSQL(); $row = Environment::getService('connection')->fetchAssoc($sql); $this->assertEquals(42, $row['id']); $this->assertEquals(1, $row['status']); $this->assertEquals('GET|POST|PUT|DELETE', $row['methods']); $this->assertEquals('/bar', $row['path']); $this->assertEquals('Fusio\\Impl\\Controller\\SchemaApiController', $row['controller']); $this->assertEquals('a:1:{i:0;C:15:"PSX\\Data\\Record":517:{a:2:{s:4:"name";s:6:"config";s:6:"fields";a:3:{s:6:"status";i:4;s:4:"name";s:1:"1";s:7:"methods";a:4:{i:0;C:15:"PSX\\Data\\Record":70:{a:2:{s:4:"name";s:6:"method";s:6:"fields";a:1:{s:4:"name";s:3:"GET";}}}i:1;C:15:"PSX\\Data\\Record":71:{a:2:{s:4:"name";s:6:"method";s:6:"fields";a:1:{s:4:"name";s:4:"POST";}}}i:2;C:15:"PSX\\Data\\Record":70:{a:2:{s:4:"name";s:6:"method";s:6:"fields";a:1:{s:4:"name";s:3:"PUT";}}}i:3;C:15:"PSX\\Data\\Record":73:{a:2:{s:4:"name";s:6:"method";s:6:"fields";a:1:{s:4:"name";s:6:"DELETE";}}}}}}}}', $row['config']); }
public function testItem() { $body = <<<XML <?xml version="1.0" encoding="UTF-8"?> <item> \t<title>Star City</title> \t<link>http://liftoff.msfc.nasa.gov/news/2003/news-starcity.asp</link> \t<description>How do Americans get ready to work with Russians aboard the International Space Station? They take a crash course in culture, language and protocol at Russia's <a href="http://howe.iki.rssi.ru/GCTC/gctc_e.htm">Star City</a>.</description> \t<pubDate>Tue, 03 Jun 2003 09:39:21 GMT</pubDate> \t<guid>http://liftoff.msfc.nasa.gov/2003/06/03.html#item573</guid> </item> XML; $request = new Message(array('Content-Type' => 'application/rss+xml'), $body); $rss = Environment::getService('importer')->import(new Rss(), $request); $item = $rss->current(); $this->assertInstanceOf('PSX\\Data\\RecordInterface', $item); $this->assertEquals('Star City', $item->getTitle()); $this->assertEquals('http://liftoff.msfc.nasa.gov/news/2003/news-starcity.asp', $item->getLink()); $this->assertEquals('How do Americans get ready to work with Russians aboard the International Space Station? They take a crash course in culture, language and protocol at Russia\'s <a href="http://howe.iki.rssi.ru/GCTC/gctc_e.htm">Star City</a>.', $item->getDescription()); $this->assertEquals(new \DateTime('Tue, 03 Jun 2003 09:39:21 GMT'), $item->getPubDate()); $this->assertEquals('http://liftoff.msfc.nasa.gov/2003/06/03.html#item573', $item->getGuid()); }
public function testGetForm() { $action = new SqlFetchRow(); $action->setConnection(Environment::getService('connection')); $this->assertInstanceOf('Fusio\\Form\\Container', $action->getForm()); }