I'm new to unit-testing, so this is maybe a little dumb question.
Imagine, we have a simple model method.
public function get_all_users($uid = false, $params = array()){
$users = array();
if(empty($uid) && empty($params)){return $users;}
$this->db->from('users u');
if($uid){
$this->db->where('u.id',(int)$id);
}
if(!empty($params)){
if(isset($params['is_active']){
$this->db->where('u.status ', 'active');
}
if(isset($params['something_else']){ // some more filter actions}
}
$q = $this->db->get();
if($q->num_rows()){
foreach($q->result_array() as $user){
$users[$user['id']] = $user;
}
}
$q->free_result();
return $users;
}
The question is how a _good test would be written for it?
UPD: I guess, the best unit-testing library for CI is Toast, so example i'm looking for, preferable be written using it.
Thanks.
I'm using toast too, and mostly I use it to test a model methods. To do it, first truncate all table values, insert a predefined value, then get it. This is the example of test I used in my application:
class Jobads_tests extends Toast
{
function Jobads_tests()
{
parent::Toast(__FILE__);
// Load any models, libraries etc. you need here
$this->load->model('jobads_draft_model');
$this->load->model('jobads_model');
}
/**
* OPTIONAL; Anything in this function will be run before each test
* Good for doing cleanup: resetting sessions, renewing objects, etc.
*/
function _pre()
{
$this->adodb->Execute("TRUNCATE TABLE `jobads_draft`");
}
/**
* OPTIONAL; Anything in this function will be run after each test
* I use it for setting $this->message = $this->My_model->getError();
*/
function _post()
{
$this->message = $this->jobads_draft_model->display_errors(' ', '<br/>');
$this->message .= $this->jobads_model->display_errors(' ', '<br/>');
}
/* TESTS BELOW */
function test_insert_to_draft()
{
//default data
$user_id = 1;
//test insert
$data = array(
'user_id' => $user_id,
'country' => 'ID',
'contract_start_date' => strtotime("+1 day"),
'contract_end_date' => strtotime("+1 week"),
'last_update' => time()
);
$jobads_draft_id = $this->jobads_draft_model->insert_data($data);
$this->_assert_equals($jobads_draft_id, 1);
//test update
$data = array(
'jobs_detail' => 'jobs_detail',
'last_update' => time()
);
$update_result = $this->jobads_draft_model->update_data($jobads_draft_id, $data);
$this->_assert_true($update_result);
//test insert_from_draft
$payment_data = array(
'activation_date' => date('Y-m-d', strtotime("+1 day")),
'duration_amount' => '3',
'duration_unit' => 'weeks',
'payment_status' => 'paid',
'total_charge' => 123.45
);
$insert_result = $this->jobads_model->insert_from_draft($jobads_draft_id, $payment_data);
$this->_assert_true($insert_result);
//draft now must be empty
$this->_assert_false($this->jobads_draft_model->get_current_jobads_draft($user_id));
}
}
I'm using AdoDB in my application, but don't get confuse with that. You can do $this->db inside the test controller, after you load the database library. You can put it in autoload so it will automatically loaded.
See that in my code, before the test is run, the table is truncated. After run, I will get any error that might occured. I do assert for a predefined insert and update. Using Toast to test the model will make you sure that the model's method doing exactly the task that you want it to do. Make the test that you need, and make sure you cover all the possibilities of input and output values.
Related
I am very much new to laravel framework.
I have one form , which i need to update on submit button click.
when submit button clicks control goes to controller.php 's update() function .
But I am unable to edit any field's value.
here is my code.
public function update($id)
{
//echo "<pre>";print_r(Input::all());exit;
$product = $this->product->find($id);
$input = Input::only('designer', 'sku', 'name', 'display_name', 'description', 'price', 'main_category', 'sub_category', 'lead_time', 'sizing', 'woven', 'body_fabric', 'lining_fabric', 'fit', 'primary_color', 'secondary_color', 'care_label', 'neck_type', 'closure', 'trims', 'special_finishings', 'image1', 'image2', 'image3', 'image4', 'image5','top', 'combo_products', 'keywords', 'visibility', 'featured');
//echo "<pre>";print_r($input);exit;
try
{
$this->adminNewProductForm->validate($input);
} catch(\Laracasts\Validation\FormValidationException $e)
{
return Redirect::back()->withInput()->withErrors($e->getErrors());
}
$slug = Str::slug(Input::get('name'));
$slug = $this->product->getSlug($slug);
$input = array_add($input, 'slug', $slug);
DB::transaction(function() use($product, $input)
{
$product->fill($input)->save();
$stock_count = 0;
if(!empty(Input::get('xsmall_size')))
{
$rows = DB::table('products_variants')->where('product_id', $product->id)->where('variant_name', 'XS')->get();
$stock_count += Input::get('xsmall_stock');
if(!empty($rows))
{
DB::table('products_variants')->where('product_id', $product->id)->where('variant_name', 'XS')->update(array('variant_specs' => Input::get('xsmall_size'), 'price_change' => Input::get('xsmall_price'), 'total_stock' => Input::get('xsmall_stock'), 'stock_used' => 0));
} else {
DB::table('products_variants')->insert(array('product_id' => $product->id, 'variant_name' => 'XS', 'variant_specs' => Input::get('xsmall_size'), 'price_change' => Input::get('xsmall_price'), 'total_stock' => Input::get('xsmall_stock'), 'stock_used' => 0));
}
}
$input = array();
$input['flagship_status'] = Input::get('flagship_status');
if(Input::get('flagship_status'))
{
$input['stock_count'] = Input::get('small_stock');
}else {
$input['stock_count'] = $stock_count;
}
$product->fill($input)->save();
});
//echo "<pre>";print_r(Input::all());exit;
return Redirect::back()->withFlashMessage('Product Updated Successfully!');
}
Also I cant understand , what is going on by this line ? because i did not find validate function anywhere in my code.
$this->adminNewProductForm->validate($input);
I need to update table products not products_variants.
validate is inherited from the FormRequst class.
https://laravel.com/api/5.0/Illuminate/Foundation/Http/FormRequest.html#method_validate
You've provided too much code and too little information. You said you need to update a specific table, but yet there are two lines where you are very intentionally manually updating a database entry.
This is one of them:
DB::table('products_variants')->where('product_id', $product->id)->where('variant_name', 'XS')->update(array('variant_specs' => Input::get('xsmall_size'), 'price_change' => Input::get('xsmall_price'), 'total_stock' => Input::get('xsmall_stock'), 'stock_used' => 0));
When you call this:
$product->fill($input)->save();
It also saves 'dirty' (modified) models that also belong to it, which can include products_variants relationships. From the sound of it, you are incorrectly applying changes directly through SQL, and then the model's save method is overwriting it.
You seem unclear about what your code is actually doing, and I would strongly suggest simplifying it down and adding in code as you begin to understand what each line does. I think your question is the byproduct of copying an example and adding your own work without understanding how Laravel handles relationships and models. There is almost never a good reason to use raw SQL or DB statements.
I'm new to Laravel and at the moment I have a piece of code in a Controller which without the while loop it works, it retrieves my query from the database.
public function dash($id, Request $request) {
$user = JWTAuth::parseToken()->authenticate();
$postdata = $request->except('token');
$q = DB::select('SELECT * FROM maps WHERE user_id = :id', ['id' => $id]);
if($q->num_rows > 0){
$check = true;
$maps = array();
while($row = mysqli_fetch_array($q)) {
$product = array(
'auth' => 1,
'id' => $row['id'],
'url' => $row['url'],
'locationData' => json_decode($row['locationData']),
'userData' => json_decode($row['userData']),
'visible' => $row['visible'],
'thedate' => $row['thedate']
);
array_push($maps, $product);
}
} else {
$check = false;
}
return response()->json($maps);
}
I am trying to loop through the returned data from $q and use json_decode on 2 key/val pairs but I can't even get this done right.
Don't use mysqli to iterate over the results (Laravel doesn't use mysqli). Results coming back from Laravel's query builder are Traversable, so you can simply use a foreach loop:
$q = DB::select('...');
foreach($q as $row) {
// ...
}
Each $row is going to be an object and not an array:
$product = array(
'auth' => 1,
'id' => $row->id,
'url' => $row->url,
'locationData' => json_decode($row->locationData),
'userData' => json_decode($row->userData),
'visible' => $row->visible,
'thedate' => $row->thedate
);
You're not using $postdata in that function so remove it.
Do not use mysqli in Laravel. Use models and/or the DB query functionality built in.
You're passing the wrong thing to mysqli_fetch_array. It's always returning a non-false value and that's why the loop never ends.
Why are you looping over the row data? Just return the query results-- they're already an array. If you want things like 'locationData' and 'userData' to be decoded JSON then use a model with methods to do this stuff for you. Remember, with MVC you should always put anything data related into models.
So a better way to do this is with Laravel models and relationships:
// put this with the rest of your models
// User.php
class User extends Model
{
function maps ()
{
return $this->hasMany ('App\Map');
}
}
// Maps.php
class Map extends Model
{
// you're not using this right now, but in case your view needs to get
// this stuff you can use these functions
function getLocationData ()
{
return json_decode ($this->locationData);
}
function getUserData ()
{
return json_decode ($this->userData);
}
}
// now in your controller:
public function dash ($id, Request $request) {
// $user should now be an instance of the User model
$user = JWTAuth::parseToken()->authenticate();
// don't use raw SQL if at all possible
//$q = DB::select('SELECT * FROM maps WHERE user_id = :id', ['id' => $id]);
// notice that User has a relationship to Maps defined!
// and it's a has-many relationship so maps() returns an array
// of Map models
$maps = $user->maps ();
return response()->json($maps);
}
You can loop over $q using a foreach:
foreach ($q as $row) {
// Do work here
}
See the Laravel docs for more information.
I'm trying to build a visitors counter in Laravel....
I don't know what the best place is to put the code inside so that it loads on EVERY page... But I putted it inside of the routes.php....
I think I'll better place it inside of basecontroller?
But okay, My code looks like this now:
//stats
$date = new \DateTime;
$check_if_exists = DB::table('visitor')->where('ip', $_SERVER['REMOTE_ADDR'])->first();
$get_visit_day = DB::table('visitor')->select('visit_date')->where('ip', $_SERVER['REMOTE_ADDR'])->first();
$value = date_create($get_visit_day->visit_date);
if(!$check_if_exists)
{
DB::table('visitor')->insert(array('ip' => $_SERVER['REMOTE_ADDR'], 'hits' => '1', 'visit_date' => $date));
}else{
DB::table('visitor')->where('ip', $_SERVER['REMOTE_ADDR'])->increment('hits');
}
$value = date_create($get_visit_day->visit_date);
if ($check_if_exists && date_format($value, 'd') != date('d')) {
DB::table('visitor')->insert(array('ip' => $_SERVER['REMOTE_ADDR'], 'hits' => '1', 'visit_date' => $date));
}
That works fine, but the problem is, my database columns always add a new value.
So this is my database:
From the table 'visitor'.
It keeps adding a new IP, hit and visit_date...
How is it possible to just update the hits from today (the day) and if the day is passed, to set a new IP value and count in that column?
I'm not 100% sure on this, but you should be able to do something like this. It's not tested, and there may be a more elegant way to do it, but it's a starting point for you.
Change the table
Change the visit_date (datetime) column into visit_date (date) and visit_time (time) columns, then create an id column to be the primary key. Lastly, set ip + date to be a unique key to ensure you can't have the same IP entered twice for one day.
Create an Eloquent model
This is just for ease: make an Eloquent model for the table so you don't have to use Fluent (query builder) all the time:
class Tracker extends Eloquent {
public $attributes = [ 'hits' => 0 ];
protected $fillable = [ 'ip', 'date' ];
protected $table = 'table_name';
public static function boot() {
// Any time the instance is updated (but not created)
static::saving( function ($tracker) {
$tracker->visit_time = date('H:i:s');
$tracker->hits++;
} );
}
public static function hit() {
static::firstOrCreate([
'ip' => $_SERVER['REMOTE_ADDR'],
'date' => date('Y-m-d'),
])->save();
}
}
Now you should be able to do what you want by just calling this:
Tracker::hit();
Looking at your code and reading your description, I’m assuming you want to calculate number of hits from an IP address per day. You could do this using Eloquent’s updateOrNew() method:
$ip = Request::getClientIp();
$visit_date = Carbon::now()->toDateString();
$visitor = Visitor::findOrNew(compact('ip', 'visit_date'));
$visitor->increment('hits');
However, I would add this to a queue so you’re not hitting the database on every request and incrementing your hit count can be done via a background process:
Queue::push('RecordVisit', compact('ip', 'visit_date'));
In terms of where to bootstrap this, the App::before() filter sounds like a good candidate:
App::before(function($request)
{
$ip = $request->getClientIp();
$visit_date = Carbon::now()->toDateString();
Queue::push('RecordVisit', compact('ip', 'visit_date'));
);
You could go one step further by listening for this event in a service provider and firing your queue job there, so that your visit counter is its own self-contained component and can be added or removed easily from this and any other projects.
Thanks to #Joe for helping me fulley out!
#Martin, you also thanks, but the scripts of #Joe worked for my problem.
The solution:
Tracker::hit();
Inside my App::before();
And a new class:
<?php
class Tracker Extends Eloquent {
public $attributes = ['hits' => 0];
protected $fillable = ['ip', 'date'];
public $timestamps = false;
protected $table = 'visitor';
public static function boot() {
// When a new instance of this model is created...
static::creating(function ($tracker) {
$tracker->hits = 0;
} );
// Any time the instance is saved (create OR update)
static::saving(function ($tracker) {
$tracker->visit_date = date('Y-m-d');
$tracker->visit_time = date('H:i:s');
$tracker->hits++;
} );
}
// Fill in the IP and today's date
public function scopeCurrent($query) {
return $query->where('ip', $_SERVER['REMOTE_ADDR'])
->where('date', date('Y-m-d'));
}
public static function hit() {
static::firstOrCreate([
'ip' => $_SERVER['REMOTE_ADDR'],
'date' => date('Y-m-d'),
])->save();
}
}
Named 'tracker' :)
public $attributes = ['hits' => 0];
protected $fillable = ['ip', 'date'];
public $timestamps = false;
protected $table = 'trackers';
public static function boot() {
// When a new instance of this model is created...
parent::boot();
static::creating(function ($tracker) {
$tracker->hits = 0;
} );
// Any time the instance is saved (create OR update)
static::saving(function ($tracker) {
$tracker->visit_date = date('Y-m-d');
$tracker->visit_time = date('H:i:s');
$tracker->hits++;
} );
}
// Fill in the IP and today's date
public function scopeCurrent($query) {
return $query->where('ip', $_SERVER['REMOTE_ADDR'])
->where('date', date('Y-m-d'));
}
public static function hit() {
/* $test= request()->server('REMOTE_ADDR');
echo $test;
exit();*/
static::firstOrCreate([
'ip' => $_SERVER['REMOTE_ADDR'],
'date' => date('Y-m-d'),
// exit()
])->save();
}
In laravel 5.7 it required parent::boot() otherwise it will show Undefined index: App\Tracker
https://github.com/laravel/framework/issues/25455
This is what i did its very basic but can easily build it up and add filters on visitors per day month year etc..
i added the following code to the web.php file above all the routes to run on each request on the site so no matter what page the visitor landed on it will save the ip addess to the database only if its unique so one visitor wont keep addding to the visitor count
// Web.php
use App\Models\Visitor
$unique_ip = true;
$visitors = Visitor::all();
foreach($visitors as $visitor){
if($visitor->ip_address == request()->ip()){
$unique_ip = false;
}
}
if($unique_ip == true){
$visitor = Visitor::create([
'ip_address' => request()->ip(),
]);
}
Routes...
the model is straight forward just has a ip addess field
I'm converting a database from being managed by SQL dumps to being managed by schemas and migrations. Part of this is seeding data. I've based what I'm doing from the schema example on CakePhp's page about Schemas.
The weird thing is that the first table to be seeded with data works without problem, and the second fails with an error like Table users for model User was not found in datasource default. This happens even if I change which table will be seeded: the first one succeeds (and I've checked in the database that the data is there) and the next one to be seeded fails.
I've also checked the error message against the database, and every table it complains about not existing does actually exist.
My 'schema.php' looks like this:
class AppSchema extends CakeSchema {
public function before($event = array()) {
return true;
}
private function create_many($class_name, $entries){
App::uses('ClassRegistry', 'Utility');
$class = ClassRegistry::init($class_name);
foreach($entries as $entry){
$class->create();
$class->save(array($class_name => $entry));
}
}
private function create_many_kv($class_name, $keys, $values_matrix){
$entries = array();
foreach($values_matrix as $values){
array_push($entries, array_combine($keys, $values));
}
$this->create_many($class_name, $entries);
}
public function after($event = array()) {
if (isset($event['create'])) {
switch ($event['create']) {
case 'users':
$this->create_many('User', array(
array('emailaddress' => 'email',
'password' => 'hash',
'role_id' => 1
),
array('emailaddress' => 'email2',
'password' => 'hash',
'role_id' => 3)
));
break;
case 'other_table':
$this->create_many('OtherTable', array(
array('id' => 1,
'name' => 'datum'),
array('id' => 2,
'name' => 'datum2')
));
break;
etc.
The answer for me here was to populate all of the tables after the last table has been created.
My best hypothesis for why this didn't work as described in the question is that Cake is caching the database structure in memory, and this isn't updated when the new tables are added. I can't find any documentation about clearing that structure cache so a workaround is the closest thing to a solution for now.
When inserting data to more than one table you’ll need to flush the database cache after each table is created. Cache can be disabled by setting $db->cacheSources = false in the before action().
public $connection = 'default';
public function before($event = array()) {
$db = ConnectionManager::getDataSource($this->connection);
$db->cacheSources = false;
return true;
}
So far, I have figured out how to return a typical JSON response in Zend Framework 2. First, I added the ViewJsonStrategy to the strategies section of the view_manager configuration. Then, instead of returning a ViewModel instance from the controller action, I return a JsonModel instance with all my variables set.
Now that I've figured that piece out, I need to understand how to render a view and return it within that JSON response. In ZF1, I was able to use $this->view->render($scriptName), which returned the HTML as a string. In ZF2, the Zend\View\View::render(...) method returns void.
So... how can I render an HTML view script and return it in a JSON response in one request?
This is what I have right now:
if ($this->getRequest()->isXmlHttpRequest()) {
$jsonModel = new JsonModel(...);
/* #todo Render HTML script into `$html` variable, and add to `JsonModel` */
return $jsonModel;
} else {
return new ViewModel(...);
}
OK, i think i finally understood what you're doing. I've found a solution that i think matches your criteria. Though i am sure that there is room for improvement, as there's some nasty handwork to be done...
public function indexAction()
{
if (!$this->getRequest()->isXmlHttpRequest()) {
return array();
}
$htmlViewPart = new ViewModel();
$htmlViewPart->setTerminal(true)
->setTemplate('module/controller/action')
->setVariables(array(
'key' => 'value'
));
$htmlOutput = $this->getServiceLocator()
->get('viewrenderer')
->render($htmlViewPart);
$jsonModel = new JsonModel();
$jsonModel->setVariables(array(
'html' => $htmlOutput,
'jsonVar1' => 'jsonVal2',
'jsonArray' => array(1,2,3,4,5,6)
));
return $jsonModel;
}
As you can see, the templateMap i create is ... nasty ... it's annoying and i'm sure it can be improved by quite a bit. It's a working solution but just not a clean one. Maybe somehow one would be able to grab the, probably already instantiated, default PhpRenderer from the ServiceLocator with it's template- and path-mapping and then it should be cleaner.
Thanks to the comment ot #DrBeza the work needed to be done could be reduced by a fair amount. Now, as I'd initially wanted, we will grab the viewrenderer with all the template mapping intact and simply render the ViewModel directly. The only important factor is that you need to specify the fully qualified template to render (e.g.: "$module/$controller/$action")
I hope this will get you started though ;)
PS: Response looks like this:
Object:
html: "<h1>Hello World</h1>"
jsonArray: Array[6]
jsonVar1: "jsonVal2"
You can use more easy way to render view for your JSON response.
public function indexAction() {
$partial = $this->getServiceLocator()->get('viewhelpermanager')->get('partial');
$data = array(
'html' => $partial('MyModule/MyPartView.phtml', array("key" => "value")),
'jsonVar1' => 'jsonVal2',
'jsonArray' => array(1, 2, 3, 4, 5, 6));
$isAjax = $this->getRequest()->isXmlHttpRequest());
return isAjax?new JsonModel($data):new ViewModel($data);
}
Please note before use JsonModel class you need to config View Manager in module.config.php file of your module.
'view_manager' => array(
.................
'strategies' => array(
'ViewJsonStrategy',
),
.................
),
it is work for me and hope it help you.
In ZF 3 you can achieve the same result with this code
MyControllerFactory.php
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
$renderer = $container->get('ViewRenderer');
return new MyController(
$renderer
);
}
MyController.php
private $renderer;
public function __construct($renderer) {
$this->renderer = $renderer;
}
public function indexAction() {
$htmlViewPart = new ViewModel();
$htmlViewPart
->setTerminal(true)
->setTemplate('module/controller/action')
->setVariables(array('key' => 'value'));
$htmlOutput = $this->renderer->render($htmlViewPart);
$json = \Zend\Json\Json::encode(
array(
'html' => $htmlOutput,
'jsonVar1' => 'jsonVal2',
'jsonArray' => array(1, 2, 3, 4, 5, 6)
)
);
$response = $this->getResponse();
$response->setContent($json);
$response->getHeaders()->addHeaders(array(
'Content-Type' => 'application/json',
));
return $this->response;
}
As usual framework developer mess thing about AJAX following the rule why simple if might be complex Here is simple solution
in controller script
public function checkloginAction()
{
// some hosts need to this some not
//header ("Content-type: application/json"); // this work
// prepare json aray ....
$arr = $array("some" => .....);
echo json_encode($arr); // this works
exit;
}
This works in ZF1 and ZF2 as well
No need of view scrpt at all
If you use advise of ZF2 creator
use Zend\View\Model\JsonModel;
....
$result = new JsonModel($arr);
return $result;
AJAX got null as response at least in zf 2.0.0