mercredi 22 août 2018

Laravel repository testing

I'm having some trouble understanding what to test and how to do it properly.

Scenario: A user is going to make a request to fetch a paginated collection of users. The user only has access to view certain fields of this collection (for example, can view name but can't see email)

For this, I have table users, a table called element, a table called attributes, a table called user_attributes and a table called user_attribute_access.

Table users is a regular user table, with fields id, name, email

Record example:  (id 1, name someone, email someone@someone.com)

Table element represents project elements and in this specific scenario, there is an element called user. Contains fields such as id, value

Record example: (id 1, value user)

Table attributes represents the attributes of the project elements and in this specific scenario, it contains a list of id,value,type. This was made so that it would be possible to implement EAV pattern in regards of creating custom fields to a user.

Record example: (id 1, value name, type base_atribute),(id 2, value email, type base_atribute),(id 3, value sex, type non_base_atribute)

Table user_attributes contains the value for these custom attributes, with fields user_id, attribute_id and value

Record example: user_id 1, attribute_id 3, value male

This works just fine

UserController

public function index(Request $request, $userId)
{
    //This gets me a collection of user_attribute_access that contain attribute_id
    //Simplified, its a query to user_access_attributes
    $filteredFieldList = $this->userRepository->getAttributesPermissionsOfElements($userId)->filter(function ($value, $key) {
        return $value->can_read == 1;
    });

    $baseColumnList =  \App\Models\Attribute::whereIn('id', $filteredFieldList->pluck('attribute_id')->toArray())
    ->where('type', 'base_atribute')->pluck('value')->toArray();

    $customColumnIdList = \App\Models\Attribute::whereIn('id', $filteredFieldList->pluck('attribute_id')->toArray())
    ->where('type','!=', 'non_base_atribute')->pluck('id')->toArray();

    //This paginate is has an added parameter because:
    //1. I want to be able to select only the fields he has access to from the table users
    //2. I want to be able to select only the fields he has access to from table user_attributes, that are the custom ones

    $paginatedUsers = $this->userRepository->paginate(15, !empty($baseColumnList) ? $baseColumnList : array('*'), !empty($customColumnIdList) ? $customColumnIdList : null);

    return $this->response(UserResource::collection($paginatedUsers),"Users",200);
}

My question is: I know the expected output because of already inserted records and tested them. I want to write tests so I know that if code is changed, the test will alert me that a user is seeing a certain field (or not seeing) and I have no idea how to approach it or to begin with.

Aucun commentaire:

Enregistrer un commentaire