Tools for non regression testing on REST API? - symfony

I have developed a project with a symfony server as backend and a mobile application as frontend.
I am unemployed but I hope to start my own business :)
What tool(s) should I use for non regression testing ?
Thank you for your help!

I suppose you don't use API Platform. It provides the ApiTestCase that provides several assertions to test JSON responses :
class BooksTest extends ApiTestCase
{
// This trait provided by AliceBundle will take care of refreshing the database content to a known state before each test
use RefreshDatabaseTrait;
public function testGetCollection(): void
{
// The client implements Symfony HttpClient's `HttpClientInterface`, and the response `ResponseInterface`
$response = static::createClient()->request('GET', '/books');
$this->assertResponseIsSuccessful();
// Asserts that the returned content type is JSON-LD (the default)
$this->assertResponseHeaderSame('content-type', 'application/ld+json; charset=utf-8');
// Asserts that the returned JSON is a superset of this one
$this->assertJsonContains([
'#context' => '/contexts/Book',
'#id' => '/books',
'#type' => 'hydra:Collection',
'hydra:totalItems' => 100,
'hydra:view' => [
'#id' => '/books?page=1',
'#type' => 'hydra:PartialCollectionView',
'hydra:first' => '/books?page=1',
'hydra:last' => '/books?page=4',
'hydra:next' => '/books?page=2',
],
]);
As you can see, in this example, the /books endpoint of the API is tested. But you can also use the standard WebTestCase provided by Symfony to do this manually.

Related

How to configure a Translatable Entity in EasyAdmin?

I'm using Translatable and EasyAdmin in a Symfony 5 project and I have configured 2 languages.
The issue is I need to be able to edit the different languages of a record in EasyAdmin, I have checked the docs of Translatable, EasyAdmin and Symfony, There is very little information about how to integrate database translations into EasyAdmin.
Therefore, I'm a bit stuck in terms of code, I have tried configuring setTranslationParameters() inside the entity CRUD controller and changing some configuration in the DashboardController however, I don't think this is the right approach.
Any suggestions of how to solve this issue?
Thank you for your effort and time.
as of writing, this feature doesn't exist in EasyAdmin, please see the link to the answer to the issue on Github.
https://github.com/EasyCorp/EasyAdminBundle/issues/4982
However, a work around is possible with a different package:
remove doctrine-extensions/DoctrineExtensions and then install KnpLabs/DoctrineBehaviors
install a2lix/translation-form-bundle
Create a translation field:
<?php
declare(strict_types=1);
namespace App\Controller\Admin\Field;
use A2lix\TranslationFormBundle\Form\Type\TranslationsType;
use EasyCorp\Bundle\EasyAdminBundle\Contracts\Field\FieldInterface;
use EasyCorp\Bundle\EasyAdminBundle\Field\FieldTrait;
final class TranslationField implements FieldInterface
{
use FieldTrait;
public static function new(string $propertyName, ?string $label = null, array $fieldsConfig = []): self
{
return (new self())
->setProperty($propertyName)
->setLabel($label)
->setFormType(TranslationsType::class)
->setFormTypeOptions([
'default_locale' => 'cz',
'fields' => $fieldsConfig,
]);
}
}
Use the TranslationField inside your admin CRUD controller:
public function configureFields(string $pageName): iterable
{
return [
TextField::new('title', 'title')->hideOnForm(),
TranslationField::new('translations', 'translations', [
'title' => [
'field_type' => TextType::class,
'required' => true,
]
// add more translatable properties into the array
])->setRequired(true)
->hideOnIndex()
];
}

How to get translator inside controller plugin on ZF3

I want to create a plugin to use zend-i18n/translate on controller. On zf2 I have a controller plugin that does this for me, but on zf3 I could not get this to work. How can I use zend-i18n inside a controller or via controller plugin with zf3?
==========
I just found what I need here on zf doc: https://docs.zendframework.com/zend-mvc-i18n/services/#mvctranslator-and-translatorfactory
if you already have config the translator as factory on your module.config.php, you can inject on your controller plugin.
You can virtually do the same as the answer that #hkulekci referred to in his comment.
'service_manager' => [
'factories' => [
\Zend\I18n\Translator\TranslatorInterface::class => \Zend\I18n\Translator\TranslatorServiceFactory::class,
]
]
and
'controller_plugins' => [
'invokables' => [
'translate' => \Zend\I18n\View\Helper\Translate::class
]
]
After that you can get the translate plugin like in your controller action methods like this:
public someAction(){
$translator = $this->translate;
}
Check the Zend Framework documentation or this Zend Framework blog for more details on the controller plugin manager.
For translate in model and controller, I did this in my module.config.php
'service_manager' => [
'factories' => [
\Zend\I18n\Translator\Translator::class => \Zend\I18n\Translator\TranslatorServiceFactory::class,
],
],
Then from my controller or model which has serviceContainer initialised I do:
$this->myVar = $serviceContainer->get(\Zend\I18n\Translator\Translator::class);
Then I can access it by doing
$this->myVar->translate('lorem ipsum');

Silex token authentication

I create my first app with silex. Only logged in users can use the app. In the first page i create a login form, so the user can authenticate. My security provider look like:
$app->register(new Silex\Provider\SecurityServiceProvider(), array(
'security.firewalls' => array(
'secure_area_edison' => array(
'pattern' => '^/admin/',
'form' => array('login_path' => '/', 'check_path' => '/admin/login_check'),
'logout' => array('logout_path' => '/admin/logout', 'invalidate_session' => true),
'users' => function () use ($app) {
return new App\Services\UserProvider($app['db']);
},
),
)
));
Every url after '/admin' require that the user was successfull authenticated. Everything works fine and now i want to extend my app with an API. I create a new controller which retrieves data from database and return a JSON reponse, this work also fine.
But how can the user authenticate for this API? Should i create a new column in my user table like "hash" or "token"? Users which will retrieve the JSON Response must send the token in every get request, is this the correct way?
The url can look:
/admin/api/allProducts/token/<TOKEN>
you should use token base authentication instead of passing token in every get request.
refer : https://github.com/thcolin/silex-simpleuser-jwt

HTTP client Cakephp 3 ignores json body

I'm currently writing a RESTful API in Cakephp 3 whereby I need to test a POST operation through http://host.com/api/pictures. The code for the test:
<?php
namespace App\Test\TestCase\Controller;
use App\Controller\Api\UsersController;
use Cake\TestSuite\IntegrationTestCase;
use Cake\Network\Http\Client;
use Cake\Network\Http\FormData;
class ApiPicturesControllerTest extends IntegrationTestCase{
public $fixtures = [
'app.users',
'app.comments',
'app.albums',
'app.users_albums'
];
public function testAdd(){
// $data = new FormData();
$accessToken ='eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjksImV4cCI6MTQ1NzYyOTU3NH0.NnjXWEQCno3PUiwHhnUCBjiknR-NlmT42oPLA5KhuYo';
$http = new Client([
'headers' => ['Authorization' => 'Bearer ' . $accessToken, 'Content-Type' => 'application/json']
]);
$data = [
"album_id" => 1,
"link" => "http://www.google.com",
"description" => "testtesttest",
"favorite" => true
];
$result = $http->post('http://vecto.app/api/pictures/add.json', $data, ['type'=>'json']);
// $this->assertResponseOk();
// debug($result);
}
}
When I try to debug the result I get a 'cannot add or update child row' while I'm sure the responding id does exists
(the fixtures does have the id's too). Additionally, the log indicates that it only tries to insert the create/update rows. Therefore, I'm pretty sure the data is ignored but however I can't find a solution. I already tried different combination of headers like only application/json for Accept, application/json for Content-Type etc. I'm using the CRUD plugin for Cakephp to pass the data to an add function.
Postman output
Furthermore, I tried the Postman Chrome plugin to save the data and that actually does work. Does anyone know what I'm doing wrong in the test?
That's not how the integration test case is ment to be used. You are dispatching an external, real request, which will leave the test environment, while you should use the request dispatching tools that the integration test case supplies, that is
IntegrationTestCase::get()
IntegrationTestCase::post()
IntegrationTestCase::put()
etc...
These methods will dispatch simulated requests that do not leave the test environment, which is crucial for things to work properly, as you want to use test connections, inspect possible exceptions, have access to the used session, etc...
ie, you should do something along the lines of
$accessToken = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjksImV4cCI6MTQ1NzYyOTU3NH0.NnjXWEQCno3PUiwHhnUCBjiknR-NlmT42oPLA5KhuYo';
$this->configRequest([
'headers' => [
'Authorization' => 'Bearer ' . $accessToken,
'Content-Type' => 'application/json'
]
]);
$data = [
"album_id" => 1,
"link" => "http://www.google.com",
"description" => "testtesttest",
"favorite" => true
];
$this->post('/api/pictures/add.json', json_encode($data));
Note that a content type of application/json will require you to send raw JSON data! If you don't actually need/want to test parsing of raw input, then you could skip that header, and pass the array as data instead.
See also
Cookbook > Testing > Controller Integration Testing
API > \Cake\TestSuite\IntegrationTestCase

Need to pull fields from an issue in Sitecore

I'm working with SiteCore and I need to pull some data out of the software via either that API or the SQL database using a PHP script. The reason I say both are possible is because even if the database changes later on, that doesn't matter to me.
Anyway...
I'm trying to pull any data fields that I can get from a particular issue. This is my SOAP code so far, and it connects to the service and such, but the return isn't what I need...
try
{
$client = new SoapClient('http://localhost:8083/sitecore/shell/webservice/service.asmx?WSDL');
$credentials = array('Password' => 'mypassword','Username' => 'sitecore\myusername');
$Current_Issue = array(
'id' => '{043B69BA-3175-4184-812F-C925CE80324E}',
//'language' => 'en',
//'version' => '1',
//'allFields' => 'true',
'databaseName' => 'web',
'credentials' => $credentials
);
$response = $client->GetItemMasters($Current_Issue);
print_r($response);
}
catch(SoapFault $e)
{
echo $e->getMessage();
}
catch(Exception $e)
{
echo $e->getMessage();
}
This is my output:
stdClass Object
(
[GetItemMastersResult] => stdClass Object
(
[any] => <sitecore xmlns=""/>
)
)
ANY help is appreciated. If anybody knows an example SQL query that I can use, that would be just as useful as an alternative method.
Thanks
If you are running Sitecore 6.5 / 6.6 you may want to take a look at the Sitecore Item Web API which was released yesterday (5/11/12).
http://sdn.sitecore.net/Products/Sitecore%20Item%20Web%20API.aspx
This allows you to perform RESTful operations against Sitecore items without the need for the old web service / SOAP interface. Using this module you can receive a JSON representation of a Sitecore item or collection of items and even post back changes. You may find it easier to work with :)
If you have to use the SOAP interface, are you sure that your items are published ? Try changing the databaseName -> 'master' and see if you get any results. Other things to check are the permissions of the user credentials you are using.

Resources