Update tests

This commit is contained in:
Matthew Ross 2020-05-11 19:12:48 -04:00
parent ee2a0f4f0c
commit 8e733aa12c
7 changed files with 499 additions and 23 deletions

View File

@ -21,6 +21,11 @@ class DataMock {
$user = R::load('user', $userId);
$user->active_token = $jwt;
if ($userId == 3) {
$user->security_level = SecurityLevel::UNPRIVILEGED;
}
R::store($user);
return $jwt;

View File

@ -5,6 +5,8 @@ use RedBeanPHP\R;
class AttachmentsTest extends PHPUnit\Framework\TestCase {
private $attachments;
const diskfilename = '638df56a901567375d06757aeac8317366eb0ade';
public static function setUpBeforeClass(): void {
try {
R::setup('sqlite:tests.db');
@ -77,6 +79,65 @@ class AttachmentsTest extends PHPUnit\Framework\TestCase {
$actual->body->data->alerts[0]['text']);
}
public function testGetAttachmentByHash() {
$request = new RequestMock();
$request->header = [DataMock::GetJwt()];
$args = [];
$args['hash'] = AttachmentsTest::diskfilename;
$actual = $this->attachments->getAttachmentByHash($request,
new ResponseMock(), $args);
$this->assertEquals('No attachment found for hash ' .
AttachmentsTest::diskfilename . '.',
$actual->body->data->alerts[0]['text']);
$this->createAttachment();
$request->header = [DataMock::GetJwt()];
$this->attachments = new Attachments(new LoggerMock());
$actual = $this->attachments->getAttachmentByHash($request,
new ResponseMock(), $args);
$this->assertEquals('success', $actual->body->data->status);
$this->assertEquals(2, count($actual->body->data->data));
}
public function testGetAttachmentByHashInvalid() {
$request = new RequestMock();
$request->hasHeader = false;
$args = [];
$args['hash'] = AttachmentsTest::diskfilename;
$actual = $this->attachments->getAttachmentByHash($request,
new ResponseMock(), $args);
$this->assertEquals('error', $actual->body->data->alerts[0]['type']);
}
public function testGetAttachmentByHashForbidden() {
$this->createAttachment();
$args = [];
$args['hash'] = AttachmentsTest::diskfilename;
$actual = $this->attachments->getAttachmentByHash(new RequestMock(),
new ResponseMock(), $args);
$this->assertEquals('error', $actual->body->data->alerts[0]['type']);
DataMock::CreateBoardAdminUser();
$request = new RequestMock();
$request->header = [DataMock::GetJwt(2)];
$this->attachments = new Attachments(new LoggerMock());
$actual = $this->attachments->getAttachmentByHash($request,
new ResponseMock(), $args);
$this->assertEquals('Access restricted.',
$actual->body->data->alerts[0]['text']);
}
public function testAddAttachment() {
$task = R::dispense('task');
R::store($task);
@ -96,6 +157,8 @@ class AttachmentsTest extends PHPUnit\Framework\TestCase {
new ResponseMock(), null);
$this->assertEquals('Attachment added.',
$actual->body->data->alerts[0]['text']);
rmdir('uploads/');
}
public function testAddAttachmentInvalid() {
@ -107,6 +170,8 @@ class AttachmentsTest extends PHPUnit\Framework\TestCase {
new ResponseMock(), null);
$this->assertEquals('failure', $actual->body->data->status);
$this->assertEquals('error', $actual->body->data->alerts[0]['type']);
rmdir('uploads/');
}
public function testAddAttachmentForbidden() {
@ -136,6 +201,75 @@ class AttachmentsTest extends PHPUnit\Framework\TestCase {
new ResponseMock(), null);
$this->assertEquals('Access restricted.',
$actual->body->data->alerts[0]['text']);
rmdir('uploads/');
}
public function testUploadFile() {
$request = new RequestMock();
$request->header = [DataMock::GetJwt()];
$args = [];
$args['hash'] = AttachmentsTest::diskfilename;
$actual = $this->attachments->uploadFile($request,
new ResponseMock(), $args);
$this->assertEquals('Error uploading attachment. Please try again.',
$actual->body->data->alerts[0]['text']);
$this->createAttachment();
$request->header = [DataMock::GetJwt()];
$this->attachments = new Attachments(new LoggerMock());
$_FILES['file'] = [];
$_FILES['file']['tmp_name'] = 'asdf';
$_FILES['file']['error'] = 1;
$actual = $this->attachments->uploadFile($request,
new ResponseMock(), $args);
$this->assertEquals('failure', $actual->body->data->status);
$this->assertEquals(1, count($actual->body->data->data));
$_FILES['file'] = [];
$_FILES['file']['tmp_name'] = 'asdf';
$_FILES['file']['error'] = 0;
$this->createAttachment();
$request->header = [DataMock::GetJwt()];
$this->attachments = new Attachments(new LoggerMock());
$actual = $this->attachments->uploadFile($request,
new ResponseMock(), $args);
$this->assertEquals('success', $actual->body->data->status);
$this->assertEquals(1, count($actual->body->data->data));
}
public function testUploadFileForbidden() {
DataMock::CreateBoardAdminUser();
$this->createAttachment();
$request = new RequestMock();
$request->header = [DataMock::GetJwt(2)];
$args = [];
$args['hash'] = AttachmentsTest::diskfilename;
$this->attachments = new Attachments(new LoggerMock());
$actual = $this->attachments->uploadFile($request,
new ResponseMock(), $args);
$this->assertEquals('Access restricted.',
$actual->body->data->alerts[0]['text']);
$this->attachments = new Attachments(new LoggerMock());
$request->header = [DataMock::GetJwt(3)];
$actual = $this->attachments->uploadFile($request,
new ResponseMock(), $args);
$this->assertEquals('Insufficient privileges.',
$actual->body->data->alerts[0]['text']);
}
public function testRemoveAttachment() {
@ -224,6 +358,7 @@ class AttachmentsTest extends PHPUnit\Framework\TestCase {
$attachment->name = 'file.png';
$attachment->user_id = 1;
$attachment->diskfilename = AttachmentsTest::diskfilename;
$task->xownAttachmentList[] = $attachment;
$column->xownTaskList[] = $task;

View File

@ -94,7 +94,7 @@ class UsersTest extends PHPUnit\Framework\TestCase {
$args['id'] = 1;
$request = new RequestMock();
$request->header = [DataMock::GetJwt(3)];
$request->header = [DataMock::GetJwt(4)];
$this->users = new Users(new LoggerMock());

View File

@ -4,7 +4,7 @@ import {
HttpTestingController
} from '@angular/common/http/testing';
import { BoardService } from '../../../src/app/board/board.service';
import { BoardService } from 'src/app/board/board.service';
describe('BoardService', () => {
let injector: TestBed;
@ -16,7 +16,7 @@ describe('BoardService', () => {
expect(req.request.method).toEqual(method);
if (isError) {
req.flush({ alerts: [{}] }, { status: 500, statusText: '' });
req.flush({ alerts: [{}], data: [] }, { status: 500, statusText: '' });
} else {
req.flush({ data: [] });
}
@ -185,6 +185,22 @@ describe('BoardService', () => {
testCall('api/activity/task/1', 'GET', true);
});
it('adds a comment', () => {
service.addComment(<any>{ id: 1 }).subscribe(response => {
expect(response.data.length).toEqual(0);
});
testCall('api/comments', 'POST', true);
});
it('handles errors on comment add', () => {
service.addComment(null).subscribe(() => {}, response => {
expect(response.alerts.length).toEqual(1);
});
testCall('api/comments', 'POST');
});
it('updates a comment', () => {
service.updateComment(<any>{ id: 1 }).subscribe(response => {
expect(response.data.length).toEqual(0);
@ -217,6 +233,54 @@ describe('BoardService', () => {
testCall('api/comments/1', 'DELETE', true);
});
it('adds an attachment', () => {
service.addAttachment(<any>{ id: 1 }).subscribe(response => {
expect(response.data.length).toEqual(0);
});
testCall('api/attachments', 'POST');
});
it('handles errors on attachment add', () => {
service.addAttachment(<any>{ id: 1 }).subscribe(response => {
expect(response.alerts.length).toEqual(1);
});
testCall('api/attachments', 'POST', true);
});
it('removes an attachment', () => {
service.removeAttachment(1).subscribe(response => {
expect(response.data.length).toEqual(0);
});
testCall('api/attachments/1', 'DELETE');
});
it('handles errors on attachment remove', () => {
service.removeAttachment(1).subscribe(response => {
expect(response.alerts.length).toEqual(1);
});
testCall('api/attachments/1', 'DELETE', true);
});
it('uploads a file', () => {
service.uploadAttachment(null, 'asdf').subscribe(response => {
expect(response.data.length).toEqual(0);
});
testCall('api/upload/asdf', 'POST');
});
it('handles errors on file upload', () => {
service.uploadAttachment(null, 'asdf').subscribe(response => {
expect(response.alerts.length).toEqual(1);
});
testCall('api/upload/asdf', 'POST', true);
});
it('refreshes the API token', () => {
service.refreshToken();
testCall('api/refresh', 'POST');

View File

@ -2,6 +2,7 @@ import { TestBed, ComponentFixture } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { FormsModule } from '@angular/forms';
import { DomSanitizer } from '@angular/platform-browser';
import { ColumnDisplayComponent } from '../../../../src/app/board/column/column.component';
import { TaskDisplayComponent } from '../../../../src/app/board/task/task.component';
@ -36,18 +37,26 @@ describe('ColumnDisplay', () => {
HttpClientTestingModule,
FormsModule,
RouterTestingModule,
SharedModule
SharedModule,
],
declarations: [
ColumnDisplayComponent,
TaskDisplayComponent
TaskDisplayComponent,
],
providers: [
AuthService,
NotificationsService,
ModalService,
StringsService,
BoardService
BoardService,
{
provide: DomSanitizer,
useValue: {
sanitize: (_: any, val: string) => val,
bypassSecurityTrustResourceUrl: (val: string) => val,
bypassSecurityTrustHtml: (val: string) => val,
},
},
]
}).compileComponents();
});
@ -72,6 +81,13 @@ describe('ColumnDisplay', () => {
expect(component.templateElement.classList.contains('collapsed')).toEqual(true);
});
it('gets a username', () => {
component.activeBoard = <any>{ users: [<any>{ id: 1, username: 'hi' }] };
const username = component.userName(1);
expect(username).toEqual('hi');
});
it('sorts tasks', () => {
component.columnData = { tasks: [
{ position: 2, due_date: '1/1/2018', points: 1 },
@ -121,6 +137,8 @@ describe('ColumnDisplay', () => {
});
it('calls a service to add a task', () => {
component.columnData = { id: 1 } as any;
component.addTask();
expect(component.saving).toEqual(false);
@ -132,6 +150,11 @@ describe('ColumnDisplay', () => {
component.addTask();
expect(component.saving).toEqual(false);
(component.boardService.addTask as any) = () => {
return { subscribe: (_: any, err: any) => { err('Err'); } }
}
component.addTask();
(component.boardService.addTask as any) = () => {
return { subscribe: (fn: any) => fn({
status: 'success',
@ -144,6 +167,29 @@ describe('ColumnDisplay', () => {
expect(component.saving).toEqual(false);
});
it('handles drop events', () => {
const prev = { data: {} };
const evt = {
currentIndex: 0,
previousContainer: prev,
container: prev
}
component.activeBoard = {
columns: [{ id: 1, tasks: [{ id: 1 }, { id: 2 }] }, { id: 3 }]
} as any;
component.moveItemInArray = () => true;
component.transferArrayItem = () => true;
component.drop(evt as any, 0);
expect(component.activeBoard.columns[0].tasks[0].position).toEqual(1);
evt.previousContainer = { data: {} };
component.drop(evt as any, 0);
expect(component.activeBoard.columns[0].tasks[0].position).toEqual(1);
});
it('calls a service to update a task', () => {
component.updateTask();
expect(component.saving).toEqual(false);
@ -197,6 +243,86 @@ describe('ColumnDisplay', () => {
expect(called).toEqual(true);
});
it('handles file input changes', () => {
const file = { test: true };
component.fileChange(file as any);
expect(component.fileUpload).toEqual(file);
});
it('calls a service to add a file', () => {
let called = false;
component.notes.noteAdded.subscribe(() => { called = true; });
component.addFile();
expect(called).toEqual(true);
component.fileUpload = {
name: 'test.png',
type: 'image/png',
};
component.activeUser = { id: 1 } as any;
component.viewModalProps = { id: 1, attachments: [] } as any;
(component.boardService.addAttachment as any) = () => {
return { subscribe: (fn: any) => fn({ status: 'error' } as any) };
};
component.addFile();
expect(component.fileUploading).toEqual(false);
(component.boardService.addAttachment as any) = () => {
return { subscribe: (fn: any) => fn({
status: 'success',
data: [{}, { id: 3, diskfilename: 'asdfghjkl' }],
alerts: [{}]
}) };
};
(component.boardService.uploadAttachment as any) = () => {
return { subscribe: (fn: any) => fn({ status: 'success', alerts: [{}] }) };
};
component.addFile();
expect(component.fileUploading).toEqual(false);
});
it('opens a file viewer in a new window', () => {
spyOn(window, 'open');
component.viewFile('asdf');
expect(window.open).toHaveBeenCalledWith('./files/asdf', 'tb-file-view');
});
it('provides a way to get a the URL for a file', () => {
const url = component.getUrl('asdf').toString();
expect(url).toEqual('./api/uploads/asdf');
});
it('calls a service to remove a file', () => {
(component.boardService.removeAttachment as any) = () => {
return { subscribe: (fn: any) => fn({ status: 'error', alerts: [] }) };
};
component.attachmentToRemove = { id: 0 } as any;
component.removeAttachment();
(component.boardService.removeAttachment as any) = () => {
return { subscribe: (fn: any) => fn({
status: 'success',
alerts: [{}],
}) };
};
component.viewModalProps.attachments = [{ id: 0 } as any];
component.removeAttachment();
expect(component.viewModalProps.attachments.length).toEqual(0);
});
it('calls a service to add a comment', () => {
component.viewModalProps.id = 0;
component.addComment();
@ -208,21 +334,22 @@ describe('ColumnDisplay', () => {
expect(component.newComment).toEqual('');
(component.boardService.updateTask as any) = () => {
return { subscribe: (fn: any) => fn({ status: 'error' } as any) };
(component.boardService.addComment as any) = () => {
return { subscribe: (fn: any) => fn({ status: 'error', alerts: [] } as any) };
};
component.newComment = 'Testing.';
component.addComment();
expect(component.newComment).toEqual('');
(component.boardService.updateTask as any) = () => {
(component.boardService.addComment as any) = () => {
return { subscribe: (fn: any) => fn({ status: 'success', data: [{}, [
mockTask, { id: 2 }
]] } as any) };
]], alerts: [{}] } as any) };
};
component.activeBoard = {
columns: [{ id: 1, tasks: [{ id: 1 }, { id: 2 }] }, { id: 2 }]
columns: [{ id: 1, tasks: [{ id: 1 }, { id: 2 }] }, { id: 3 }]
} as any;
component.addComment();
@ -431,4 +558,32 @@ describe('ColumnDisplay', () => {
expect(component.viewModalProps.column_id).toEqual(1);
});
it('gets a comment converted from markdown', () => {
component.activeBoard = { issue_trackers: [] } as any;
const comment = component.getComment('# Testing');
expect(comment).toEqual('<h1 id="testing">Testing</h1>\n');
});
it('gets a username by user id', () => {
component.activeBoard = {
users: [{ id: 1, username: 'test' } as any]
} as any;
const uname = component.getUserName(1);
expect(uname).toEqual('test');
});
it('can call board update with an emitter', () => {
let called = false;
component.onUpdateBoards.subscribe(() => { called = true; });
component.callBoardUpdate();
expect(called).toEqual(true);
});
});

View File

@ -0,0 +1,56 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { FileViewerComponent } from 'src/app/files/file-viewer.component';
import { FileViewerService } from 'src/app/files/file-viewer.service';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { NotificationsService, AuthService } from 'src/app/shared/services';
import { SharedModule } from 'src/app/shared/shared.module';
describe('FileViewer', () => {
let component: FileViewerComponent;
let fixture: ComponentFixture<FileViewerComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
HttpClientTestingModule,
RouterTestingModule,
SharedModule,
],
declarations: [
FileViewerComponent,
],
providers: [
AuthService,
FileViewerService,
NotificationsService,
]
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(FileViewerComponent);
component = fixture.componentInstance;
});
it('can be constructed', () => {
expect(component).toBeTruthy();
});
it('implements ngOnInit', () => {
(component.service.getAttachmentInfo as any) = () => {
return { subscribe: (fn: any) => fn({
alerts: [{}],
data: [{}, { diskfilename: 'asdf' }],
status: 'success'
}) }
}
component.ngOnInit();
expect(component.isLoaded).toEqual(true);
expect(component.fileUrl).toBeTruthy();
});
});

View File

@ -0,0 +1,61 @@
import { TestBed, getTestBed } from '@angular/core/testing';
import {
HttpTestingController,
HttpClientTestingModule
} from '@angular/common/http/testing';
import { FileViewerService } from 'src/app/files/file-viewer.service';
describe('FileViewerService', () => {
let injector: TestBed;
let service: FileViewerService;
let httpMock: HttpTestingController;
const testCall = (url: string, method: string, isError = false) => {
const req = httpMock.expectOne(url);
expect(req.request.method).toEqual(method);
if (isError) {
req.flush({ alerts: [{}], data: [] }, { status: 500, statusText: '' });
} else {
req.flush({ data: [] });
}
};
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [FileViewerService]
});
injector = getTestBed();
service = injector.get(FileViewerService);
httpMock = injector.get(HttpTestingController);
});
afterEach(() => {
httpMock.verify()
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it('gets attachment info', () => {
service.getAttachmentInfo('asdf').subscribe(response => {
expect(response.data.length).toEqual(0);
});
testCall('api/attachments/hash/asdf', 'GET');
});
it('handles errors when getting all boards', () => {
service.getAttachmentInfo('asdf').subscribe(() => {}, response => {
expect(response.alerts.length).toEqual(1);
});
testCall('api/attachments/hash/asdf', 'GET', true);
});
});