mardi 29 janvier 2019

How to test and mock guzzle responses in different situations?

I want to test my API controller that using some guzzle requests from another services. I have one request for making a download link.

  1. this is my API route

    Route::group(['prefix' => '/v1'], function () {
    Route::get('/exampledl', 'DownloadController@downloadChecker');
    });
    
    
  2. DownloadChecker controller checks if user is admin or subscriber makes a guzzle request to one of my services on a different domain, if not do another Guzzle request to another service and for each situations responses are different. This is a part of controller checks admin role.

    $client = new Client();
    try {
        $response = $client->request('GET', 'https://www.example.com/api/user?u=' . $request->uid);
        $json = \GuzzleHttp\json_decode($response->getBody()->getContents(), True);
    
        // if user doesn't exist in CM
    
        //this part has been written to avoid repeating code
        if (array_key_exists('user', $json) && $json['user'] == null) {
            abort(403);
        }
        elseif (in_array("administrator", $json['Roles'])) {
            User::create([
                'uid'               => (int)$request->uid,
                'subscription.role' => 'administrator',
            ]);
            $client = new Client();
    $response = $client->request('GET', "https://vod.example2.com/vod/2.0/videos/{$a_id}?secure_ip={$u_ip}", [
        'headers' => [
            'authorization' => '**********'
        ]
    ]);
    $json = \GuzzleHttp\json_decode($response->getBody()->getContents(), TRUE);
    
    if (isset($json['data']['mp4_videos'])) {
        $links = [];
        foreach ($json['data']['mp4_videos'] as $mp_video) {
            if (stripos($mp_video, "h_144") !== false) {
                $links['144p'] = $mp_video;
            }
            elseif (stripos($mp_video, "h_240") !== false) {
                $links['240p'] = $mp_video;
            }
            elseif (stripos($mp_video, "h_360") !== false) {
                $links['360p'] = $mp_video;
            }
            elseif (stripos($mp_video, "h_480") !== false) {
                $links['480p'] = $mp_video;
            }
            elseif (stripos($mp_video, "h_720") !== false) {
                $links['720p'] = $mp_video;
            }
            elseif (stripos($mp_video, "h_1080") !== false) {
                $links['1080p'] = $mp_video;
            }
        }
        }
    
    
  3. one of my tests.

    public function test_user_notExist_admin()
    {
    $client = new Client();
    $response = $client->request('GET', 'https://www.example.com/api/user_days_and_roles?u=' . request()->uid);
    $json = \GuzzleHttp\json_decode($response->getBody()->getContents(), True);
    
    $this->get('/api/v1/exampledl?uid=1&n_id=400&u_ip=104.58.1.45&arvan_id=a81498a9')
        ->assertStatus(200)
        ->assertSee('links');
    
    $this->assertDatabaseHas('users', [
        'uid'               => (int)request('uid'),
        'subscription.role' => 'administrator',
    ]);
    }
    
    

There are some other conditions check and I'm not sure how to mock these different situations.

Should I make unit test for every situations? Or is there any way to make guzzle in test environment return a custom response? Or any other way?



via Chebli Mohamed

Laravel not retrieving milliseconds in DateTime columns

In Laravel, I have some columns with milliseconds. Note that some other columns do not have milliseconds (e.g. created_at, updated_at).

Here is my migration:

Schema::create('brands', function (Blueprint $table) {
    $table->increments('id');
    $table->dateTime('sync_date_time', 3);
    $table->timestamps();
});

My model is simply:

class Brand extends Model {}

Yet when I have a record with milliseconds (e.g. 2018-12-19 01:40:46.512) , and execute:

$brand->sync_date_time;

It always returns a string without the milliseconds portion (e.g. 2018-12-19 01:40:46).

Why is this happening, and how can I fix this issue?

Note that this is not a Carbon issue, as I am not using Carbon for this field at all.



via Chebli Mohamed

How to fix poor looking Processing message in laravel-datatables?

In my laravel 5.7/ blade / jQuery v3.3.1 / Bootstrap v4.1.2 app I use

I use "yajra/laravel-datatables-oracle": "~8.0" library and it works ok, but when data are retrieving I do not like how Processing message looks like : https://imgur.com/a/Otebuku

I can hardly read this message and it is over my table header and as common it looks poor. I have blade block :

    <div class="table-responsive">
        <table class="table table-bordered table-striped text-primary" id="get-storage-space-dt-listing-table">
            <thead>
            <tr>
                <th>Id</th>
                <th>Box Room No.</th>
                <th>Selling range</th>
                <th>Warehouse</th>
                <th>Level</th>
                <th>Storage Capacity</th>
                <th>Check In</th>
                <th>Paid through date</th>
                <th>Job Ref No</th>
                <th>Status</th>
                <th>Created At</th>
                <th></th>
                <th></th>
            </tr>
            </thead>
        </table>

    </div>

and javascript initialization :

backendStorageSpace.prototype.StorageSpacesLoad = function () {
    Mustache.tags = ["<%", "%>"];
    var template = $('#storage_space_details_info_template').html();

    var ins = this
    oTable = $('#get-storage-space-dt-listing-table').DataTable({
        processing: true,
        serverSide: true,
        "lengthChange": true,
        "lengthMenu": this_backendLengthMenuArray,
        ajax: {
            url: this_backend_home_url + '/admin/get-box-rooms-dt-listing',
            data: function (d) {
                d.filter_status = $("#filter_status").val();
                ...
            },
        }, // ajax: {

        columns: [

            {data: 'id', name: 'id'},
            {data: 'number', name: 'number'},
            {data: 'selling_range', name: 'selling_range'},
            {data: 'warehouse_name', name: 'warehouse_name'},
            {data: 'level', name: 'level'},
            {data: 'storage_capacity_name', name: 'storage_capacity_name'},
            {data: 'check_in_date', name: 'check_in_date'},
            {data: 'check_out_date', name: 'check_out_date'},

            {data: 'job_ref_no', name: 'job_ref_no'},
            {data: 'status', name: 'status'},
            {data: 'created_at', name: 'created_at'},
            {data: 'action', name: 'action', orderable: false, searchable: false},
            {data: 'action_delete', name: 'action_delete', orderable: false, searchable: false}

        ],

        "drawCallback": function (settings, b) {
            ...

I search and did not find where this message appearance is controled ? If there is a way to make it look better, say show this message below of table row with head block ?

Thanks!



via Chebli Mohamed

jQuery.ajaxSetup is not a function

my code is On head

<meta name="csrf-token" content="" />

On form

<input type="hidden" name="_token" value="">

Script

<script src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(e) {
  jQuery.ajaxSetup({
    headers: {
      'X-CSRF-TOKEN': jQuery('meta[name="csrf-token"]').attr('content')
    }
  });
});
jQuery('form').on('submit', function(e) {
  var msg = jQuery('#msg').val();


  e.preventDefault();

  jQuery.ajax({
    type: 'post',
    url: '/sendmsg',
    data: jQuery('#send-msg').serialize(),
    success: function() {
      alert('form was submitted');
    }
  });

});
</script>

Error is jQuery.ajaxSetup is not a function



via Chebli Mohamed

TypeError: this.cards.filter is not a function

i´ll do have a little problem with my Component displaying and filtering Data from my Database. Its returning a JSON Object and if this is getting to big im getting a "TypeError: this.cards.filter is not a function" error. In my testview its working but in the real database its crashing.

Code:

<div class="container sidebar-container">
            <ul class="nav justify-content-center nav-tabs">
                <li class="nav-item">
                    <a class="nav-link navbar" v-on:click.prevent="cardsFilterKey = 'all'" :class="{ active: cardsFilterKey == 'all'}">Alle</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link navbar" v-on:click.prevent="cardsFilterKey = 'livingspaces'" :class="{ active: cardsFilterKey == 'livingspaces'}">Wohnraum</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link navbar" v-on:click.prevent="cardsFilterKey = 'therapies'" :class="{ active: cardsFilterKey == 'therapies'}">Therapien</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link navbar" v-on:click.prevent="cardsFilterKey = 'news'" :class="{ active: cardsFilterKey == 'news'}">News</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link navbar" v-on:click.prevent="cardsFilterKey = 'achievements'" :class="{ active: cardsFilterKey == 'achievements'}">Erfolge</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link navbar" v-on:click.prevent="cardsFilterKey = 'events'" :class="{ active: cardsFilterKey == 'events'}">Events</a>
                </li>
            </ul>
            </div>

Displaying Data:

<div class="col-md-4" v-for="(card, index) in cardsFilter" style="padding-bottom:2em;">
                    <div class="card w-100 text-center card-div" style="width:18rem">
                    <img src="/img/card2.jpg" class="card-img-top">
                        <div class="card-body">
                            <h5 class="card-title"></h5>
                            <h6 class="card-subtitle mb-2 text-muted"></h6>
                            <p class="card-text"></p>
                            <button @click="showTextModal(index)" type="button" class="btn btn-primary">Zeige mehr Infos</button>
                        </div>
                    </div>
                    </div>

Filtering Data:

<script>
export default {
    data() {
        return {
            cards: [],
            validationErrors: '',
            uri: process.env.MIX_CARDS_URL,
            isHidden: true,
            cards_modal: [],
            cardsFilterKey: 'all'
        }
    },

    methods: {
        showTextModal(index) {
            $("#textModal").modal("show");
            this.cards_modal = this.cards[index];
        },
        loadCards() {
            axios.get(this.uri).then(response=>{
                this.cards = response.data.sortedData;
                this.loading=true;
            })
        }
    },

    computed: {
        cardsFilter() {
            return this[this.cardsFilterKey]
        },
        all(){
            return this.cards
        },
        news() {
            return this.cards.filter((card) => card.category == 'news')
        },
        achievements() {
            return this.cards.filter((card) => card.category == 'achievements')
        },
        events() {
            return this.cards.filter((card) => card.category == 'events')
        },
        livingspaces() {
            return this.cards.filter((card) => card.category == 'livingspaces')
        },
        therapies() {
            return this.cards.filter((card) => card.category == 'therapies')
        }
    },

    mounted() {
        this.loadCards();
    }
}
</script>

Some ideas why this is happening only on the live-server not on my localhost:8000? Same configuration same files same database just other data inside the database



via Chebli Mohamed

Conflict when make dynamic routing in Laravel

im new in Laravel. I want to make routing in Laravel.

  • domain/{member_name} -> to MemberController
  • domain/{admin_name} -> to AdminController

But when I access domain/example-admin-name, it only go to MemberController.

I know I can make domain/member/{member_name} and domain/admin/{admin_name}.

But I want it to be simple and only have one segment uri



via Chebli Mohamed

Why application hungs when using 'count' keyword as localScope function name

I have class Reservation in php Laravel 5. I create localScope query. When i use special word count, which is aggregate for sum in scope function name, my application hang up. When i change function name to something not like keyword like total, everything works fine. Why application hangs when i use special keyword ? How does process works. Stackoverflow ?

class Reservation extends Model { public function scopecount($query){ return $query->count(); }

I return it as:

$count = Reservation::currentMonth()->count();

My function currentMonth:

public function scopecurrentMonth($query){ return $query->where('date_from','>=', Carbon::now()->startOfMonth()) ->where('date_to','<=', Carbon::now()->endOfMonth()); } So why it hungs? When i change name count to total:

public function scopetotal($query){ return $query->count(); }

and

$count = Reservation::currentMonth()->total();

everything works fine.

So why it hungs ?



via Chebli Mohamed