Skip to content

Commit

Permalink
FileController upload action tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Nemmo committed Feb 4, 2016
1 parent 77a8c8f commit 1927ef6
Show file tree
Hide file tree
Showing 16 changed files with 156 additions and 19 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,5 @@
.idea/
build/
vendor/
tests/uploads/
tests/data/db.sqlite
2 changes: 1 addition & 1 deletion phpunit.xml.dist
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
processIsolation="false"
stopOnFailure="false">
<testsuites>
<testsuite name="Yii2 Imperavi Test Suite">
<testsuite name="Yii2 Attachments test suite">
<directory>./tests</directory>
</testsuite>
</testsuites>
Expand Down
3 changes: 2 additions & 1 deletion src/Module.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use nemmo\attachments\models\File;
use yii\base\Exception;
use yii\helpers\ArrayHelper;
use yii\helpers\FileHelper;
use yii\i18n\PhpMessageSource;

Expand All @@ -27,7 +28,7 @@ public function init()
throw new Exception('Setup {storePath} and {tempPath} in module properties');
}

$this->rules = array_replace(['maxFiles' => 3], $this->rules);
$this->rules = ArrayHelper::merge(['maxFiles' => 3], $this->rules);
$this->defaultRoute = 'file';
$this->registerTranslations();
}
Expand Down
23 changes: 14 additions & 9 deletions src/controllers/FileController.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@
use nemmo\attachments\models\File;
use nemmo\attachments\models\UploadForm;
use nemmo\attachments\ModuleTrait;
use Yii;
use yii\helpers\FileHelper;
use yii\helpers\Url;
use yii\web\Controller;
use yii\web\Response;
use yii\web\UploadedFile;

class FileController extends Controller
Expand All @@ -19,8 +21,8 @@ public function actionUpload()
$model = new UploadForm();
$model->file = UploadedFile::getInstances($model, 'file');

if ($model->rules()[0]['maxFiles'] == 1) {
$model->file = UploadedFile::getInstances($model, 'file')[0];
if ($model->rules()[0]['maxFiles'] == 1 && sizeof($model->file) == 1) {
$model->file = $model->file[0];
}

if ($model->file && $model->validate()) {
Expand All @@ -34,12 +36,15 @@ public function actionUpload()
} else {
$path = $this->getModule()->getUserDirPath() . DIRECTORY_SEPARATOR . $model->file->name;
$model->file->saveAs($path);
$result['uploadedFiles'][] = $model->file->name;
}
return json_encode($result);
Yii::$app->response->format = Response::FORMAT_JSON;
return $result;
} else {
return json_encode([
Yii::$app->response->format = Response::FORMAT_JSON;
return [
'error' => $model->getErrors('file')
]);
];
}
}

Expand All @@ -48,14 +53,14 @@ public function actionDownload($id)
$file = File::findOne(['id' => $id]);
$filePath = $this->getModule()->getFilesDirPath($file->hash) . DIRECTORY_SEPARATOR . $file->hash . '.' . $file->type;

return \Yii::$app->response->sendFile($filePath, "$file->name.$file->type");
return Yii::$app->response->sendFile($filePath, "$file->name.$file->type");
}

public function actionDelete($id)
{
$this->getModule()->detachFile($id);

if (\Yii::$app->request->isAjax) {
if (Yii::$app->request->isAjax) {
return json_encode([]);
} else {
return $this->redirect(Url::previous());
Expand All @@ -66,7 +71,7 @@ public function actionDownloadTemp($filename)
{
$filePath = $this->getModule()->getUserDirPath() . DIRECTORY_SEPARATOR . $filename;

return \Yii::$app->response->sendFile($filePath, $filename);
return Yii::$app->response->sendFile($filePath, $filename);
}

public function actionDeleteTemp($filename)
Expand All @@ -78,7 +83,7 @@ public function actionDeleteTemp($filename)
rmdir($userTempDir);
}

if (\Yii::$app->request->isAjax) {
if (Yii::$app->request->isAjax) {
return json_encode([]);
} else {
return $this->redirect(Url::previous());
Expand Down
5 changes: 3 additions & 2 deletions src/models/UploadForm.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use nemmo\attachments\ModuleTrait;
use yii\base\Model;
use yii\helpers\ArrayHelper;
use yii\web\UploadedFile;

/**
Expand All @@ -17,7 +18,7 @@ class UploadForm extends Model
use ModuleTrait;

/**
* @var UploadedFile|Null file attribute
* @var UploadedFile[]|UploadedFile file attribute
*/
public $file;

Expand All @@ -27,7 +28,7 @@ class UploadForm extends Model
public function rules()
{
return [
array_replace([['file'], 'file'], $this->getModule()->rules)
ArrayHelper::merge(['file', 'file'], $this->getModule()->rules)
];
}
}
117 changes: 117 additions & 0 deletions tests/FileControllerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
<?php
/**
* Created by PhpStorm.
* User: Alimzhan
* Date: 2/2/2016
* Time: 9:45 PM
*/

namespace tests;

use nemmo\attachments\Module;
use Yii;
use yii\helpers\FileHelper;
use yii\web\UploadedFile;

class FileControllerTest extends \PHPUnit_Framework_TestCase
{
/**
* @inheritDoc
*/
protected function setUp()
{
FileHelper::removeDirectory(Yii::getAlias('@tests/uploads'));
UploadedFile::reset();
}

/**
* Upload action test
*/
public function testUpload1()
{
$types = ['png', 'txt', 'jpg'];
$this->generateFiles($types);
$output = Yii::$app->runAction('attachments/file/upload');
$this->assertArrayHasKey('uploadedFiles', $output);
$this->assertTrue(in_array('file.png', $output['uploadedFiles']));
$this->checkFilesExist($types);
}

public function testUpload2()
{
$types = ['png', 'txt', 'jpg', 'zip'];
$this->generateFiles($types);
$output = Yii::$app->runAction('attachments/file/upload');
$this->assertArrayHasKey('error', $output);
}

public function testUpload3()
{
Yii::$app->setModule('attachments', [
'class' => Module::className(),
'rules' => [
'maxFiles' => 1
]
]);
$types = ['png', 'zip'];
$this->generateFiles($types);
$output = Yii::$app->runAction('attachments/file/upload');
$this->assertArrayHasKey('error', $output);
}

public function testUpload4()
{
Yii::$app->setModule('attachments', [
'class' => Module::className(),
'rules' => [
'maxFiles' => 1
]
]);
$types = ['png'];
$this->generateFiles($types);
$output = Yii::$app->runAction('attachments/file/upload');
$this->assertArrayHasKey('uploadedFiles', $output);
$this->assertTrue(in_array('file.png', $output['uploadedFiles']));
$this->checkFilesExist($types);
}

public function testUpload5()
{
Yii::$app->setModule('attachments', [
'class' => Module::className(),
'rules' => [
'maxFiles' => 3,
'mimeTypes' => ['image/png', 'image/jpeg']
]
]);
$types = ['png', 'jpg', 'zip'];
$this->generateFiles($types);
$output = Yii::$app->runAction('attachments/file/upload');
var_dump($output);
$this->assertArrayHasKey('error', $output);
}

public function generateFiles($types)
{
$_FILES = [];
foreach ($types as $index => $type) {
$file = "file.$type";
$path = Yii::getAlias("@tests/files/$file");
$_FILES["UploadForm[file][$index]"] = [
'name' => $file,
'type' => mime_content_type($path),
'size' => filesize($path),
'tmp_name' => $path,
'error' => 0
];
}
}

public function checkFilesExist($types)
{
foreach ($types as $type) {
$filePath = Yii::getAlias('@tests/uploads/temp/' . Yii::$app->session->id . '/file.' . $type);
$this->assertTrue(file_exists($filePath));
}
}
}
4 changes: 3 additions & 1 deletion tests/ModuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,9 @@ public function testInitException()

public function testInit()
{
Yii::$app->language = 'ru';
Yii::$app->setModule('attachments', [
'class' => Module::className()
]);
/** @var Module $module */
$module = Yii::$app->getModule('attachments');
$this->assertEquals([
Expand Down
18 changes: 13 additions & 5 deletions tests/bootstrap.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,13 @@
* Time: 9:46 PM
*/

namespace tests;
namespace yii\web;

use Yii;

/**
* Turn on all error reports
*/
error_reporting(E_ALL | E_STRICT);

defined('YII_DEBUG') or define('YII_DEBUG', true);
Expand All @@ -20,7 +23,9 @@

Yii::setAlias('@tests', __DIR__);

// Overwrite
/**
* Overwrite functions for fake uploads
*/
function is_uploaded_file($filename)
{
return file_exists($filename);
Expand All @@ -31,10 +36,13 @@ function move_uploaded_file($filename, $destination)
return copy($filename, $destination);
}

/**
* Run yii web application
*/
new \yii\web\Application([
'id' => 'unit',
'basePath' => __DIR__,
'vendorPath' => __DIR__ . '/../vendor',
'basePath' => Yii::getAlias('@tests'),
'vendorPath' => Yii::getAlias('@tests/../vendor'),
'modules' => [
'attachments' => [
'class' => \nemmo\attachments\Module::className(),
Expand All @@ -48,7 +56,7 @@ function move_uploaded_file($filename, $destination)
],
'db' => [
'class' => \yii\db\Connection::className(),
'dsn' => 'sqlite:' . __DIR__ . '/data/db.sqlite'
'dsn' => 'sqlite:' . Yii::getAlias('@tests/data/db.sqlite')
]
]
]);
Binary file added tests/files/file.bmp
Binary file not shown.
Binary file added tests/files/file.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added tests/files/file.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added tests/files/file.mp3
Binary file not shown.
File renamed without changes
1 change: 1 addition & 0 deletions tests/files/file.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
file 1
Binary file added tests/files/file.wav
Binary file not shown.
Binary file added tests/files/file.zip
Binary file not shown.

0 comments on commit 1927ef6

Please sign in to comment.