Mock API when performing a WebTestCase and do $client->submitform() in Symfony 5 - api

I have a Test which submits a form. This form usually results in performing doing a external API call. I want to mock that because I'm not interested in the API but in the action.
Whenever I call submitForm the client is still making an external call, but I don't want that.
The test also fails because the api expects a api key which the test does not have.
class SubscriptionControllerTest extends WebTestCase
{
public function testSubscribe(): void
{
$client = static::createClient();
$userRepository = static::$container->get(UserRepository::class);
$testUser = $userRepository->findOneBy(['email' => UserFixtures::$testUser]);
$clientMock = $this->createMock(ApiClient::class);
//replace the api with the mock one
self::$container->set(ApiClient::class, $clientMock);
$client->loginUser($testUser);
$client->request('GET', '/subscription/new');
$client->submitForm('btn-submit', [
'subscribe[firstName]' => 'firstname',
'subscribe[lastName]' => 'lastname'
]);
$this->assertResponseStatusCodeSame(201);
}
}
What am I doing wrong here?

So the problem is described in this post:
https://stackoverflow.com/a/19951344/3679577
TL:DR
2 requests are being done in my test. A GET and a submitForm (POST). First one uses the proper Mock, second request rebuilds the kernel and the mocks are gone.
My solution was to just use 1 request by submitting the form with a POST request. Using the CSRF token manager to generate a csrf token:
public function testSubscribe(): void
{
$client = static::createClient();
$userRepository = static::$container->get(UserRepository::class);
$testUser = $userRepository->findOneBy(['email' => UserFixtures::$testUser]);
$csrfTokenGenerator = $client->getContainer()->get('security.csrf.token_manager');
$apiClient = $this->createMock(ApiClient::class);
$client->getContainer()->set(ApiClient::class, $apiClient);
$client->loginUser($testUser);
$client->request('POST', '/subscription/new', [
'subscribe' => [
"firstName" => 'firstname',
"lastName" => "lastname",
"_token" => $csrfTokenGenerator->getToken('subscribe')->getValue()
]
]);
$this->assertResponseRedirects('/subscription/thankyou');
}

Related

Shopware 6 : How to make work my own Request in Postman using Admin API

I have created my own Request API ( POST : {{baseUrl}}/products/create ). This API is used to create many products and returns only the total number of existing products in Shopware. I want to execute my request in postman, but I can not. There is a way to make work the request in Postman ?
ApiController.php
<?php declare(strict_types=1);
namespace TestApi\Controller\Api;
use Shopware\Core\Framework\Context;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\JsonResponse;
use Shopware\Core\Framework\Routing\Annotation\RouteScope;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
/**
* #RouteScope(scopes={"api"})
*/
class ApiController extends AbstractController
{
protected EntityRepositoryInterface $productRepository;
public function __construct(EntityRepositoryInterface $productRepository)
{
$this->productRepository = $productRepository;
}
/**
* #Route("/products/create", name="api.product.create", methods={"POST"})
*/
public function createProducts(Context $context): JsonResponse
{
$this->productRepository->create([
[
'name' => 'Product 1',
'productNumber' => 'SW1231',
'stock' => 10,
'taxId' => 'bc3f1ba6f75749c79b5b4a9d673cf9d4',
'price' => [['currencyId' => Defaults::CURRENCY, 'gross' => 50, 'net' => 25, 'linked' => false]],
],[
'name' => 'Product 2',
'productNumber' => 'SW1232',
'stock' => 10,
'taxId' => 'bc3f1ba6f75749c79b5b4a9d673cf9d4',
'price' => [['currencyId' => Defaults::CURRENCY, 'gross' => 50, 'net' => 25, 'linked' => false]],
]
], $context);
$criteria = new Criteria();
$products = $this->productRepository->search($criteria, $context);
return new JsonResponse($products->count());
}
}
Postman :
For information I have provided the Authorization header in the request.
Actually your issue lies inside your controller, you use the api route scope, which means that the api authentication mechanism should be used. But all routes with the api route scope need to start with the /api prefix in the path.
Routes without a /api or /store-api prefix are assumed to be storefront requests with the storefront authorization. You should also get an error because of the mismatch of route scope and actual api path, but probably the CSRF error is thrown before that is validated.
To fix your code use /api/products/create as the path for your custom controller action and also use the /api prefix in postman to access your route.
You're making a request against the storefront, not an api endpoint. The CSRF protection only comes into play in the storefront. Is your baseUrl missing the /api prefix? The value should be like http://localhost/api.

How to get rid of error 422 laravel in a unit test?

So I'm writing unit tests for a laravel 5.7 web app and when I test the login it gives me error 422(I know that it has something to do with invalid data, I just don't know how to fix it)
public function testRegularUserLogin_CreatedRegularUse_ReturnsStoreView()
{
$regularUser = factory( User::class)->create();
$response = $this->json('POST','/login',
[
'email' => $regularUser->email,
'password' => $regularUser->password,
'_token' => csrf_token()
]);
$response->assertStatus(200);
}
I've tried using the csrf token on the header
This is the output that test gives me
You should just mock authentication:
do something like this
public function getFakeClient()
{
$client = factory(App\User::class)->create();
$this->be($client);
Auth::shouldReceive('user')->andReturn($this->client);
Auth::shouldReceive('check')->andReturn(true);
return $this->client;
}
then
$user = $this->getFakeClient();
$user->shouldReceive('posts')->once()->andReturn(array('posts'));
as recommended by Taylor Otwell himself here.

Send email with TDD Laravel 5.6

I am doing the registration user
public function register(RegistrationUser $request)
{
$user = $this->usersRepo->create($request->all());
$user->activation_token = str_random(48);
$user->save();
Mail::to($user->email)->queue(new ActivationAccount($user->first_name, $user->last_name, $user->email, $request->input('password'), $url));
return redirect()->route('successful.registration')
}
My registration test is:
public function it_creates_a_new_user()
{
$this->withExceptionHandling();
$response = $this->get(route('register'))
->assertStatus(200);
$this->post('register', [
'first_name' => 'Juan',
'last_name' => 'Lopez',
'email' => 'jlopez#gmail.com',
'password' => 'secret',
'activation_tone' => str_random(48)
])->assertRedirect(route('successful.registration'));
$this->assertDatabaseHas('users', [
'email' => 'jlopez#gmail.com',
]);
}
I have two questions:
1) How can I write a test to send the registration email and verify that it sends and arrives well?
2) When the user clicks on his email he calls a method where the activation token is passed to activate his account
In my opinion you should use mail fake ,which will prevent mail from being sent. You may then assert that mailables were sent to users and even inspect the data they received.
please read laravel docs: https://laravel.com/docs/5.6/mocking#mail-fake
There must be a route which is handling activation token and functionality, so try to get the token and call route with specific token
Note: As a developer we need to make sure that our code works which our tests are confirming, Sending and delivering email should be not be covered as they considered to work as expected(by any email service provider).

Testing a CakePHP 3 REST API

I am developing an API on CakePHP 3 using the CRUD Plugin and ADmad's JWT plugin. I've created fixtures for all tables by importing the schema and then defining some dummy records. Now I'd like to know the best way to test my API.
Namely:
How do I set an Authorized user in my tests?
How do I call API methods in the test framework?
I don't have any code to show at the moment because I'm really not sure how to go about this in the correct way.
The one way I see to test API endpoints is by using post() method of the IntegrationTestCase suite. A very basic example:
public function testLogin()
{
// You can add this to the setUp() function to make it global
$this->configRequest([
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'x-www-form-urlencoded'
]
]);
$this->post('/auth/token', ['username' => $username, 'password' => $password]);
$this->assertResponseOk();
$this->assertResponseContains('access_token');
}
Store that access token (or pre-generate one) & use that to set authorization header.
You can send your authorization tokens like so (before EVERY request):
$this->configRequest([
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'x-www-form-urlencoded',
'Authorization' => 'Bearer ' . $token
]
]);
TIP: You can Configure::write() the Security.salt values in bootstrap.php of the test - this way the password salting works! I also found saving the salted password value in your fixture helpful.
More details in CakePHP Cookbook.

Blocking access via HTTP Authentication with Zend Framework 2

I'm trying to implement HTTP-based authentication through a Zend\Authentication\Adapter\Http as explained in the ZF2 documentation about the HTTP Authentication Adapter.
I want to block every incoming request until the user agent is authenticated, however I'm unsure about how to implement this in my module.
How would I setup my Zend\Mvc application to deny access to my controllers?
What you are looking for is probably a listener attached to the Zend\Mvc\MvcEvent::EVENT_DISPATCH event of your application.
In order, here's what you have to do to block access to any action through an authentication adapter. First of all, define a factory that is responsible for producing your authentication adapter:
namespace MyApp\ServiceFactory;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\Authentication\Adapter\Http as HttpAdapter;
use Zend\Authentication\Adapter\Http\FileResolver;
class AuthenticationAdapterFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $serviceLocator)
{
$config = $serviceLocator->get('Config');
$authConfig = $config['my_app']['auth_adapter'];
$authAdapter = new HttpAdapter($authConfig['config']);
$basicResolver = new FileResolver();
$digestResolver = new FileResolver();
$basicResolver->setFile($authConfig['basic_passwd_file']);
$digestResolver->setFile($authConfig['digest_passwd_file']);
$adapter->setBasicResolver($basicResolver);
$adapter->setDigestResolver($digestResolver);
return $adapter;
}
}
This factory will basically give you a configured auth adapter, and abstract its instantiation logic away.
Let's move on and attach a listener to our application's dispatch event so that we can block any request with invalid authentication headers:
namespace MyApp;
use Zend\ModuleManager\Feature\ConfigProviderInterface;
use Zend\ModuleManager\Feature\BootstrapListenerInterface;
use Zend\EventManager\EventInterface;
use Zend\Mvc\MvcEvent;
use Zend\Http\Request as HttpRequest;
use Zend\Http\Response as HttpResponse;
class MyModule implements ConfigProviderInterface, BootstrapListenerInterface
{
public function getConfig()
{
// moved out for readability on SO, since config is pretty short anyway
return require __DIR__ . '/config/module.config.php';
}
public function onBootstrap(EventInterface $event)
{
/* #var $application \Zend\Mvc\ApplicationInterface */
$application = $event->getTarget();
$serviceManager = $application->getServiceManager();
// delaying instantiation of everything to the latest possible moment
$application
->getEventManager()
->attach(function (MvcEvent $event) use ($serviceManager) {
$request = $event->getRequest();
$response = $event->getResponse();
if ( ! (
$request instanceof HttpRequest
&& $response instanceof HttpResponse
)) {
return; // we're not in HTTP context - CLI application?
}
/* #var $authAdapter \Zend\Authentication\Adapter\Http */
$authAdapter = $serviceManager->get('MyApp\AuthenticationAdapter');
$authAdapter->setRequest($request);
$authAdapter->setResponse($response);
$result = $adapter->authenticate();
if ($result->isValid()) {
return; // everything OK
}
$response->setBody('Access denied');
$response->setStatusCode(HttpResponse::STATUS_CODE_401);
$event->setResult($response); // short-circuit to application end
return false; // stop event propagation
}, MvcEvent::EVENT_DISPATCH);
}
}
And then the module default configuration, which in this case was moved to MyModule/config/module.config.php:
return array(
'my_app' => array(
'auth_adapter' => array(
'config' => array(
'accept_schemes' => 'basic digest',
'realm' => 'MyApp Site',
'digest_domains' => '/my_app /my_site',
'nonce_timeout' => 3600,
),
'basic_passwd_file' => __DIR__ . '/dummy/basic.txt',
'digest_passwd_file' => __DIR__ . '/dummy/digest.txt',
),
),
'service_manager' => array(
'factories' => array(
'MyApp\AuthenticationAdapter'
=> 'MyApp\ServiceFactory\AuthenticationAdapterFactory',
),
),
);
This is the essence of how you can get it done.
Obviously, you need to place something like an my_app.auth.local.php file in your config/autoload/ directory, with the settings specific to your current environment (please note that this file should NOT be committed to your SCM):
<?php
return array(
'my_app' => array(
'auth_adapter' => array(
'basic_passwd_file' => __DIR__ . '/real/basic_passwd.txt',
'digest_passwd_file' => __DIR__ . '/real/digest_passwd.txt',
),
),
);
Eventually, if you also want to have better testable code, you may want to move the listener defined as a closure to an own class implementing the Zend\EventManager\ListenerAggregateInterface.
You can achieve the same results by using ZfcUser backed by a Zend\Authentication\Adapter\Http, combined with BjyAuthorize, which handles the listener logic on unauthorized actions.
Answer of #ocramius is accept answer But you forget to describe How to write two files basic_password.txt and digest_passwd.txt
According to Zend 2 Official Doc about Basic Http Authentication:
basic_passwd.txt file contains username, realm(the same realm into your configuration) and plain password -> <username>:<realm>:<credentials>\n
digest_passwd.txt file contains username, realm(the same realm into your configuration) and password hashing Using MD5 hash -> <username>:<realm>:<credentials hashed>\n
Example:
if basic_passwd.txt file:
user:MyApp Site:password\n
Then digest_passwd.txt file:
user:MyApp Site:5f4dcc3b5aa765d61d8327deb882cf99\n
Alternatively you can use Apache Resolver for HTTP Adapter
use Zend\Authentication\Adapter\Http\ApacheResolver;
$path = 'data/htpasswd';
// Inject at instantiation:
$resolver = new ApacheResolver($path);
// Or afterwards:
$resolver = new ApacheResolver();
$resolver->setFile($path);
According to https://zendframework.github.io/zend-authentication/adapter/http/#resolvers