Browse Source

General improvements to testing environment and removed clutter (#36)

RamonRobben 4 years ago
parent
commit
bfdbe62cd7

+ 3 - 0
.gitignore

@@ -13,3 +13,6 @@ Homestead.json
 Homestead.yaml
 Homestead.yaml
 npm-debug.log
 npm-debug.log
 yarn-error.log
 yarn-error.log
+.gitignore
+.env.dev
+.env.testing

+ 21 - 0
BUILDING.md

@@ -14,3 +14,24 @@ php artisan key:generate --force
 php artisan storage:link
 php artisan storage:link
 php artisan migrate --seed --force
 php artisan migrate --seed --force
 ```
 ```
+
+## Setting up testing environment
+
+Change the .env.testing file to your needs. Then once done you need to go into your phpmyadmin to create a new database named __controlpanel_test__.
+Visit http://127.0.0.1:8080/ and create your database.
+
+Now you're ready to run the following commands which switches to the testing config, migrates the test database and seeds it.
+After that you can switch back to your dev environment again. Clear the config from cache so changes will be instantly available.
+
+```shell
+php artisan migrate --env=testing
+php artisan db:seed --env=testing
+php artisan config:cache --env=dev
+php artisan config:clear
+```
+
+Now when running tests with PHPUnit it will use your testing database and not your local development one.
+This is configured in the __phpunit.xml__. You can run your tests by running the command like this. Just type and enter.
+`./vendor/bin/phpunit`. If you don't want to type that all the time you can also use my shortcut `bin/test.sh`
+
+

+ 5 - 2
app/Classes/Pterodactyl.php

@@ -25,14 +25,17 @@ class Pterodactyl
         ])->baseUrl(env('PTERODACTYL_URL') . '/api');
         ])->baseUrl(env('PTERODACTYL_URL') . '/api');
     }
     }
 
 
+    //TODO: Extend error handling (maybe logger for more errors when debugging)
     /**
     /**
      * Get user by pterodactyl id
      * Get user by pterodactyl id
      * @param int $pterodactylId
      * @param int $pterodactylId
      * @return mixed
      * @return mixed
      */
      */
-    public static function getUser(int $pterodactylId){
+    public function getUser(int $pterodactylId){
         $response = self::client()->get("/application/users/{$pterodactylId}");
         $response = self::client()->get("/application/users/{$pterodactylId}");
-        if ($response->failed()) return null;
+        if ($response->failed()) {
+            return [];
+        }
         return $response->json()['attributes'];
         return $response->json()['attributes'];
     }
     }
 
 

+ 12 - 10
app/Console/Commands/MakeUserCommand.php

@@ -23,14 +23,17 @@ class MakeUserCommand extends Command
      */
      */
     protected $description = 'Create an admin account with the Artisan Console';
     protected $description = 'Create an admin account with the Artisan Console';
 
 
+    private Pterodactyl $pterodactyl;
+
     /**
     /**
      * Create a new command instance.
      * Create a new command instance.
      *
      *
      * @return void
      * @return void
      */
      */
-    public function __construct()
+    public function __construct(Pterodactyl $pterodactyl)
     {
     {
         parent::__construct();
         parent::__construct();
+        $this->pterodactyl = $pterodactyl;
     }
     }
 
 
     /**
     /**
@@ -44,17 +47,16 @@ class MakeUserCommand extends Command
         $password = $this->option('password') ?? $this->ask('Please specify your password.');
         $password = $this->option('password') ?? $this->ask('Please specify your password.');
 
 
         if (strlen($password) < 8) {
         if (strlen($password) < 8) {
-            print_r('Your password need to be at least 8 characters long');
-
-            return false;
+            $this->alert('Your password need to be at least 8 characters long');
+            return 0;
         }
         }
 
 
-        $response = Pterodactyl::getUser($ptero_id);
-
-        if (is_null($response)) {
-            print_r('It seems that your Pterodactyl ID isnt correct. Rerun the command and input an correct ID');
+        //TODO: Do something with response (check for status code and give hints based upon that)
+        $response = $this->pterodactyl->getUser($ptero_id);
 
 
-            return false;
+        if ($response === []) {
+            $this->alert('It seems that your Pterodactyl ID is not correct. Rerun the command and input an correct ID');
+            return 0;
         }
         }
 
 
         $user = User::create([
         $user = User::create([
@@ -73,6 +75,6 @@ class MakeUserCommand extends Command
             ['Admin', $user->role],
             ['Admin', $user->role],
         ]);
         ]);
 
 
-        return true;
+        return 1;
     }
     }
 }
 }

+ 8 - 22
app/Http/Controllers/Admin/UserController.php

@@ -19,36 +19,22 @@ use Illuminate\Validation\ValidationException;
 
 
 class UserController extends Controller
 class UserController extends Controller
 {
 {
-    /**
-     * Display a listing of the resource.
-     *
-     * @param Request $request
-     * @return Application|Factory|View|Response
-     */
-    public function index(Request $request)
-    {
-        return view('admin.users.index');
-    }
+    private Pterodactyl $pterodactyl;
 
 
-    /**
-     * Show the form for creating a new resource.
-     *
-     * @return Response
-     */
-    public function create()
+    public function __construct(Pterodactyl $pterodactyl)
     {
     {
-        //
+        $this->pterodactyl = $pterodactyl;
     }
     }
 
 
     /**
     /**
-     * Store a newly created resource in storage.
+     * Display a listing of the resource.
      *
      *
      * @param Request $request
      * @param Request $request
-     * @return Response
+     * @return Application|Factory|View|Response
      */
      */
-    public function store(Request $request)
+    public function index(Request $request)
     {
     {
-        //
+        return view('admin.users.index');
     }
     }
 
 
     /**
     /**
@@ -96,7 +82,7 @@ class UserController extends Controller
             "role" => Rule::in(['admin', 'mod', 'client', 'member']),
             "role" => Rule::in(['admin', 'mod', 'client', 'member']),
         ]);
         ]);
 
 
-        if (is_null(Pterodactyl::getUser($request->input('pterodactyl_id')))) {
+        if (is_null($this->pterodactyl->getUser($request->input('pterodactyl_id')))) {
             throw ValidationException::withMessages([
             throw ValidationException::withMessages([
                 'pterodactyl_id' => ["User does not exists on pterodactyl's panel"]
                 'pterodactyl_id' => ["User does not exists on pterodactyl's panel"]
             ]);
             ]);

+ 1 - 1
bin/startdocker.sh

@@ -1,2 +1,2 @@
 docker-compose -f docker/docker-compose.yml down
 docker-compose -f docker/docker-compose.yml down
-docker-compose -f docker/docker-compose.yml up -d --force-recreate
+docker-compose -f docker/docker-compose.yml up -d --force-recreate --remove-orphans

+ 1 - 0
bin/test.sh

@@ -0,0 +1 @@
+./vendor/bin/phpunit

+ 1 - 1
composer.json

@@ -23,7 +23,7 @@
         "socialiteproviders/discord": "^4.1",
         "socialiteproviders/discord": "^4.1",
         "spatie/laravel-activitylog": "^3.16",
         "spatie/laravel-activitylog": "^3.16",
         "yajra/laravel-datatables-oracle": "~9.0",
         "yajra/laravel-datatables-oracle": "~9.0",
-      "ext-intl": "*"
+        "ext-intl": "*"
     },
     },
     "require-dev": {
     "require-dev": {
         "facade/ignition": "^2.5",
         "facade/ignition": "^2.5",

+ 0 - 9
klad.txt

@@ -1,9 +0,0 @@
-,
-fnDrawCallback: function( oSettings ) {
-                    $('[data-toggle="popover"]').popover();
-                }
-
-
-
-
-                data-content="Delete" data-toggle="popover" data-trigger="hover" data-placement="top"

+ 5 - 4
phpunit.xml

@@ -5,8 +5,8 @@
          colors="true"
          colors="true"
 >
 >
     <testsuites>
     <testsuites>
-        <testsuite name="Tests">
-            <directory suffix="Test.php">tests</directory>
+        <testsuite name="Unit">
+            <directory suffix=".php">tests/Unit</directory>
         </testsuite>
         </testsuite>
     </testsuites>
     </testsuites>
     <coverage processUncoveredFiles="true">
     <coverage processUncoveredFiles="true">
@@ -18,11 +18,12 @@
         <server name="APP_ENV" value="testing"/>
         <server name="APP_ENV" value="testing"/>
         <server name="BCRYPT_ROUNDS" value="4"/>
         <server name="BCRYPT_ROUNDS" value="4"/>
         <server name="CACHE_DRIVER" value="array"/>
         <server name="CACHE_DRIVER" value="array"/>
-        <server name="DB_CONNECTION" value="sqlite"/>
-        <server name="DB_DATABASE" value=":memory:"/>
+        <server name="DB_CONNECTION" value="mysql"/>
+        <server name="DB_DATABASE" value="controlpanel_test"/>
         <server name="MAIL_MAILER" value="array"/>
         <server name="MAIL_MAILER" value="array"/>
         <server name="QUEUE_CONNECTION" value="sync"/>
         <server name="QUEUE_CONNECTION" value="sync"/>
         <server name="SESSION_DRIVER" value="array"/>
         <server name="SESSION_DRIVER" value="array"/>
         <server name="TELESCOPE_ENABLED" value="false"/>
         <server name="TELESCOPE_ENABLED" value="false"/>
+        <ini name="display_errors" value="true"/>
     </php>
     </php>
 </phpunit>
 </phpunit>

+ 0 - 14
tests/Unit/exampleTest.php

@@ -1,14 +0,0 @@
-<?php
-
-namespace Tests\Unit;
-
-use Tests\TestCase;
-
-class exampleTest extends TestCase
-{
-    public function test_example(): void
-    {
-        $response = $this->get('/');
-        $response->assertStatus(302);
-    }
-}

+ 52 - 0
tests/Unit/testUserCommand.php

@@ -0,0 +1,52 @@
+<?php
+
+namespace Tests\Unit;
+
+use App\Classes\Pterodactyl;
+use Illuminate\Foundation\Auth\User;
+use Illuminate\Foundation\Testing\DatabaseTransactions;
+use Illuminate\Support\Facades\DB;
+use Tests\TestCase;
+
+class testUserCommand extends TestCase
+{
+    use DatabaseTransactions;
+
+    /**
+     * A basic feature test example.
+     * @dataProvider invalidPteroIdDataProvider
+     * @param array $apiResponse
+     * @param int $expectedExitCode
+     * @return void
+     */
+    public function testMakeUserCommand(array $apiResponse, int $expectedExitCode): void
+    {
+        $pterodactyl = $this->getMockBuilder(Pterodactyl::class)->getMock();
+        $pterodactyl->expects(self::once())->method('getUser')->willReturn($apiResponse);
+
+        $this->app->instance(Pterodactyl::class, $pterodactyl);
+
+        $this->artisan('make:user')
+            ->expectsQuestion('Please specify your Pterodactyl ID.', 0)
+            ->expectsQuestion('Please specify your password.', 'password')
+            ->assertExitCode($expectedExitCode);
+    }
+
+    public function invalidPteroIdDataProvider(): array
+    {
+        return [
+            'Good Response' => [
+                'apiResponse' => [
+                    'id' => 12345,
+                    'first_name' => 'Test',
+                    'email' => 'test@test.test'
+                ],
+                'expectedExitCode' => 1
+            ],
+            'Bad Response' => [
+                'apiResponse' => [],
+                'expectedExitCode' => 0
+            ]
+        ];
+    }
+}