Skip to content

Commit 4f2a644

Browse files
Adding Database Testing config and StudentController TestCase
1 parent b5fb31c commit 4f2a644

File tree

7 files changed

+310
-16
lines changed

7 files changed

+310
-16
lines changed

composer.lock

+113-1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

config/database.php

+6
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,12 @@
3939
'prefix' => '',
4040
],
4141

42+
'sqlite_testing' => [
43+
'driver' => 'sqlite',
44+
'database' => ':memory:',
45+
'prefix' => '',
46+
],
47+
4248
'mysql' => [
4349
'driver' => 'mysql',
4450
'host' => env('DB_HOST', '127.0.0.1'),

phpunit.xml

+1
Original file line numberDiff line numberDiff line change
@@ -29,5 +29,6 @@
2929
<env name="SESSION_DRIVER" value="array"/>
3030
<env name="QUEUE_DRIVER" value="sync"/>
3131
<env name="MAIL_DRIVER" value="array"/>
32+
<env name="DB_CONNECTION" value="sqlite_testing"/>
3233
</php>
3334
</phpunit>

tests/Helpers/Seed.php

+113
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
<?php
2+
namespace Tests\Helpers;
3+
use Illuminate\Support\Facades\DB;
4+
5+
class Seed
6+
{
7+
public function datafile($file)
8+
{
9+
$data = file_get_contents($file);
10+
$data = preg_replace([ '/\w*\/\/.*\\n?/', '/[\\t\\n]/' ], ' ', $data);
11+
$data = \json_decode($data, true);
12+
if($data == null) {
13+
throw new \Exception("The data's JSON is not valid <$file> - " );
14+
}
15+
16+
static::populateDatabase($data);
17+
if(\App::environment('testing') === false) {
18+
$fileName = \substr($file, strpos($file, 'DatabaseData') + 13);
19+
echo "Seeded: {fileNmae}\n";
20+
}
21+
}
22+
23+
public static function populateDatabase($data)
24+
{
25+
foreach ($data as $model => $objects) {
26+
foreach ($objects as $object) {
27+
$attributes = static::extractObjectAttributes($object);
28+
29+
$instance = $model::create($attributes['basic']);
30+
if(!$instance) {
31+
$error = 'class: ' . $model . "\n";
32+
$error .= 'raw_data: ' . print_r($attributes['basic'], true) . "\n";
33+
$error .= 'errors: ' . print_r($instance->errors()->all(), true);
34+
throw new \Exception($error);
35+
}
36+
37+
foreach ($attributes['objects'] as $object => $objectData) {
38+
static::populateDatabase([ $object => $objectData ]);
39+
}
40+
41+
foreach ($attributes['delay']['sync'] as $attribute => $value) {
42+
$instance->{$attribute}()->sync($value);
43+
}
44+
45+
foreach ($attributes['delay']['basic'] as $attribute => $value) {
46+
$instance->{$attribute} = $value;
47+
}
48+
49+
$instance->save();
50+
}
51+
}
52+
}
53+
54+
private static function extractObjectAttributes($object)
55+
{
56+
$attributes = [ 'basic' => [], 'delay' => [ 'sync' => [], 'basic' => [] ], 'objects' => [] ];
57+
58+
foreach ($object as $key => $value) {
59+
if(is_array($value) == false && $key[0] != '*') {
60+
if (strpos($value, '::') == true) {
61+
$value = constant($value);
62+
}
63+
64+
$attributes['basic'][$key] = $value;
65+
}
66+
67+
if (strpos($key, "\\") == false && is_array($value) == true) {
68+
$attributes['delay']['sync'][$key] = $value;
69+
}
70+
71+
if ($key[0] == '*') {
72+
$key = substr($key, 1);
73+
$attributes['delay']['basic'][$key] = $value;
74+
}
75+
76+
if (strpos($key, "\\") == true) {
77+
$attributes['objects'][$key] = $value;
78+
}
79+
}
80+
81+
return $attributes;
82+
}
83+
84+
public static function import($tableName, $conditions = [], $count = 10)
85+
{
86+
$query = DB::table("vueblog.{$tableName}");
87+
if (count($conditions) > 0) {
88+
foreach ($conditions as $field => $condition) {
89+
if ($condition[0] == 'between') {
90+
$query->whereBetween($field, $condition[1]);
91+
} else {
92+
$query->where($field, $condition[0], $condition[1]);
93+
}
94+
}
95+
}
96+
97+
$records = $query->take($count)->get();
98+
foreach ($records as $record) {
99+
$record = \json_decode(json_encode($record), true);
100+
foreach ($record as $key => &$value) {
101+
if (is_null($value) || trim($value) == ' ') {
102+
unset($record[$key]);
103+
} else {
104+
$value = " '{value}' ";
105+
}
106+
}
107+
108+
$columns = implode(',', array_keys($record));
109+
$values = implode(',', array_values($record));
110+
DB::statement("INSERT INTO `{$tableName}` ({$columns}), VALUES ({$values});");
111+
}
112+
}
113+
}

tests/TestCase.php

+47-1
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,56 @@
11
<?php
22

33
namespace Tests;
4-
4+
use Tests\Helpers\Seed;
5+
use Illuminate\Support\Facades\Artisan;
6+
use Mockery\Adapter\Phpunit\MockeryPHPUnitIntegration;
57
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
68

79
abstract class TestCase extends BaseTestCase
810
{
911
use CreatesApplication;
12+
use MockeryPHPUnitIntegration;
13+
14+
protected $seeds = [];
15+
protected $shouldFallbackToDefaultSeed = true;
16+
17+
public function setUp(){
18+
parent::setUp();
19+
Artisan::call('migrate');
20+
Seed::populateDatabase(require('test-data.php'));
21+
}
22+
23+
public function tearDown(){
24+
Artisan::call('migrate:reset');
25+
$this->seeddb();
26+
}
27+
28+
public function call($method, $uri, $parameters = [], $files = [], $server = [], $content = null, $changeHistory = true)
29+
{
30+
$_SERVER['REQUEST_URI'] = $uri;
31+
$_SERVER['HTTP_HOST'] = 'http://vueblogg.test:8000/admin-home#';
32+
$_POST = $parameters;
33+
return parent::call($method, $uri, $parameters, $files, $server, $content, $changeHistory);
34+
}
35+
36+
public function seeddb()
37+
{
38+
if ($this->seeds) {
39+
$dir = $this->seedDataDirectory();
40+
foreach ($this->seeds as $seed) {
41+
$seed = trim($seed, '.php');
42+
$filepath = DIRECTORY_SEPERATOR . trim($dor, '/') . DIRECTORY_SEPERATOR . $seed . '.php';
43+
Seed::populateDatabase(require('test-data.php'));
44+
}
45+
return;
46+
}
47+
if ($this->shouldFallbackToDefaultSeed) {
48+
// \Artisan::call('seed:test');
49+
}
50+
}
51+
52+
public function seedDataDirectory()
53+
{
54+
return __DIR__;
55+
}
1056
}

tests/Unit/StudentControllerTest.php

+11-14
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,10 @@ class StudentControllerTest extends TestCase
1717
*/
1818
public function testIndex()
1919
{
20-
$student = Student::all();
21-
20+
$student = Student::find(1);
21+
22+
$this->assertEquals('sandeep', $student->first_name);
2223
$this->assertNotNull($student);
23-
$this->assertCount(30, $student);
2424
}
2525

2626
/**
@@ -31,9 +31,7 @@ public function testIndex()
3131
public function testShow()
3232
{
3333
$student = Student::find(1);
34-
35-
$this->assertNotNull($student);
36-
$this->assertEquals('Hyman', $student->first_name);
34+
$this->assertEquals('8167455196', $student->contact_number);
3735
}
3836

3937
/**
@@ -59,19 +57,18 @@ public function testUpdate()
5957
public function testCreate()
6058
{
6159
$student = new Student;
62-
$student->first_name = 'firstName';
63-
$student->middle_name = 'guardianName';
64-
$student->last_name = 'guardianName';
65-
$student->guardian_name = 'guardianName';
60+
$student->first_name = 'sandeep';
61+
$student->middle_name = 'k';
62+
$student->last_name = 'choudary';
63+
$student->guardian_name = 'knr';
6664
$student->gender = 'Male';
6765
$student->dob = '2015-09-06';
6866
$student->contact_number = 8167455196;
6967
$student->address = '7493 Legros Burg Considinefort, NH 24537';
7068
$student->save();
7169

7270
$this->assertNotNull($student->roll_number);
73-
$student = Student::all();
74-
$this->assertCount(31, $student);
71+
$this->assertContains('knr', $student->guardian_name);
7572
}
7673

7774
/**
@@ -81,10 +78,10 @@ public function testCreate()
8178
*/
8279
public function testDelete()
8380
{
84-
$student = Student::latest()->first();
81+
$student = Student::find(1);
8582
$student->delete();
8683

8784
$student = Student::all();
88-
$this->assertCount(30, $student);
85+
$this->assertCount(0, $student);
8986
}
9087
}

0 commit comments

Comments
 (0)