Adds a bunch of unit tests

This commit is contained in:
Aaron Louie 2020-01-16 16:55:33 -05:00
parent d381328472
commit 218a340b96
15 changed files with 275 additions and 137 deletions

6
package-lock.json generated
View File

@ -9917,9 +9917,9 @@
"dev": true
},
"sartography-workflow-lib": {
"version": "0.0.10",
"resolved": "https://registry.npmjs.org/sartography-workflow-lib/-/sartography-workflow-lib-0.0.10.tgz",
"integrity": "sha512-Awy80Q7h+fvNRYsCEOPFlvbZ5X0wtUEOWPmGzdxQCZB4btBkxE2utxcazzVSigl/2ai5Fmr8JIgWDn2M5y1vVQ==",
"version": "0.0.11",
"resolved": "https://registry.npmjs.org/sartography-workflow-lib/-/sartography-workflow-lib-0.0.11.tgz",
"integrity": "sha512-ZIIjBNAASRp1PN8dRptoqiV/UYIuNNmX3XfzN33ZDYqkEZcG3jSg990tBSzSo2GG4oWsJx0fd2K9153/r/t2Xw==",
"requires": {
"tslib": "^1.9.0"
}

View File

@ -41,7 +41,7 @@
"file-saver": "^2.0.2",
"hammerjs": "^2.0.8",
"rxjs": "~6.5.4",
"sartography-workflow-lib": "^0.0.10",
"sartography-workflow-lib": "^0.0.11",
"tslib": "^1.10.0",
"zone.js": "~0.9.1"
},

View File

@ -1,4 +1,4 @@
export interface NewFileDialogData {
export interface FileMetaDialogData {
fileName: string;
workflowSpecId: string;
displayName: string;

View File

@ -1,6 +0,0 @@
export const toSnakeCase = (str: string) => {
return !str ? '' : String(str)
.replace(/^\W+|\W+$/gi, '')
.replace(/\W+/gi, '_')
.toLowerCase();
};

View File

@ -0,0 +1,20 @@
import {cleanUpFilename, toSnakeCase, trimString} from './string-clean';
describe('String Cleaning Utilities', () => {
const afterTrimming = `I'm tired of wasting letters when punctuation will do, period. -Steve Martin`;
const beforeTrimming = ` 📌📍🏁 <>?:"{}[] ${afterTrimming} !@#$%^& ✌️👍👆 `;
it('converts a string to snake case', () => {
expect(toSnakeCase(beforeTrimming)).toEqual('i_m_tired_of_wasting_letters_when_punctuation_will_do_period_steve_martin');
});
it('cleans up a file name and replaces or adds the extension', () => {
expect(cleanUpFilename(beforeTrimming, 'bpmn')).toEqual(`I'm tired of wasting letters when punctuation will do, period.bpmn`);
expect(cleanUpFilename(' no extension ', 'bpmn')).toEqual('no extension.bpmn');
});
it('trims non-word characters from a string', () => {
expect(trimString(beforeTrimming)).toEqual(afterTrimming);
});
});

View File

@ -0,0 +1,23 @@
export const toSnakeCase = (str: string): string => {
str = trimString(str);
return !str ? '' : String(str)
.replace(/\W+/gi, '_')
.toLowerCase();
};
export const trimString = (str: string): string => {
return !str ? '' : String(str).replace(/^\W+|\W+$/gi, '');
};
export const cleanUpFilename = (str: string, extension: string): string => {
const arr = trimString(str).split('.');
// Add file extension, if necessary
if (arr.length < 2) {
arr.push('bpmn');
} else {
(arr[arr.length - 1]) = extension;
}
return arr.join('.');
};

View File

@ -11,12 +11,15 @@ import {MatMenuModule} from '@angular/material/menu';
import {MatSnackBarModule} from '@angular/material/snack-bar';
import {MatToolbarModule} from '@angular/material/toolbar';
import {MatTooltipModule} from '@angular/material/tooltip';
import {BrowserDynamicTestingModule} from '@angular/platform-browser-dynamic/testing';
import {BrowserAnimationsModule, NoopAnimationsModule} from '@angular/platform-browser/animations';
import {ApiService, MockEnvironment} from 'sartography-workflow-lib';
import {of} from 'rxjs';
import {ApiService, MockEnvironment, mockFileMeta0, mockWorkflowSpec0} from 'sartography-workflow-lib';
import {BPMN_DIAGRAM, BPMN_DIAGRAM_WITH_WARNINGS} from '../testing/mocks/diagram.mocks';
import {BpmnWarning} from './_interfaces/bpmn-warning';
import {AppComponent} from './app.component';
import {DiagramComponent} from './diagram/diagram.component';
import {FileMetaDialogComponent} from './file-meta-dialog/file-meta-dialog.component';
describe('AppComponent', () => {
@ -29,28 +32,29 @@ describe('AppComponent', () => {
declarations: [
AppComponent,
DiagramComponent,
FileMetaDialogComponent,
],
imports: [
BrowserAnimationsModule,
NoopAnimationsModule,
FormsModule,
HttpClientTestingModule,
MatDialogModule,
MatFormFieldModule,
MatIconModule,
MatInputModule,
MatMenuModule,
MatSnackBarModule,
MatToolbarModule,
MatTooltipModule,
NoopAnimationsModule,
ReactiveFormsModule,
MatFormFieldModule,
HttpClientTestingModule,
],
providers: [
ApiService,
{provide: 'APP_ENVIRONMENT', useClass: MockEnvironment}
]
}).compileComponents();
}).overrideModule(BrowserDynamicTestingModule, {set: {entryComponents: [FileMetaDialogComponent]}})
.compileComponents();
httpMock = TestBed.get(HttpTestingController);
fixture = TestBed.createComponent(AppComponent);
component = fixture.debugElement.componentInstance;
@ -97,7 +101,7 @@ describe('AppComponent', () => {
it('loads a diagram from URL', () => {
component.diagramUrl = 'some-url';
component.openMethod = 'url';
component['onSubmitFileToOpen']();
component.onSubmitFileToOpen();
const sReq = httpMock.expectOne(component.diagramUrl);
expect(sReq.request.method).toEqual('GET');
@ -107,7 +111,7 @@ describe('AppComponent', () => {
it('loads a diagram from URL with warnings', () => {
component.diagramUrl = 'some-url';
component.openMethod = 'url';
component['onSubmitFileToOpen']();
component.onSubmitFileToOpen();
const sReq = httpMock.expectOne(component.diagramUrl);
expect(sReq.request.method).toEqual('GET');
@ -119,7 +123,7 @@ describe('AppComponent', () => {
const newFile = new File([BPMN_DIAGRAM], 'filename.xml', {type: 'text/xml'});
component.diagramFile = newFile;
component.openMethod = 'file';
component['onSubmitFileToOpen']();
component.onSubmitFileToOpen();
expect(readFileSpy).toHaveBeenCalledWith(newFile);
});
@ -144,7 +148,7 @@ describe('AppComponent', () => {
component.diagramFile = new File([], 'filename.jpg', {type: 'image/jpeg'});
component.openMethod = 'file';
component['onSubmitFileToOpen']();
component.onSubmitFileToOpen();
const expectedParams = {
type: 'error',
error: new Error('Wrong file type. Please choose a BPMN XML file.')
@ -163,9 +167,56 @@ describe('AppComponent', () => {
it('should get the diagram file from the file input form control', () => {
const expectedFile = new File([], 'filename.jpg', {type: 'image/jpeg'});
const event = {target: {files: [expectedFile]}};
component['onFileSelected'](event);
component.onFileSelected(event);
expect(component.diagramFile).toEqual(expectedFile);
});
it('should update the diagram file on change', () => {
const initialValue = component.diagramComponent.value;
expect(initialValue).toBeFalsy();
const newValue = '<xml>newExpectedValue</xml>';
component.diagramComponent.writeValue(newValue);
expect(component.diagramComponent.value).toEqual(newValue);
expect(component.draftXml).toEqual(newValue);
});
it('should save file changes when existing diagram is modified and then saved', () => {
const saveFileChangesSpy = spyOn(component, 'saveFileChanges').and.stub();
const editFileMetaSpy = spyOn(component, 'editFileMeta').and.stub();
component.workflowSpec = mockWorkflowSpec0;
component.diagramFileMeta = mockFileMeta0;
component.diagramComponent.writeValue('<xml>newValue</xml>');
component.saveChanges();
expect(saveFileChangesSpy).toHaveBeenCalled();
expect(editFileMetaSpy).not.toHaveBeenCalled();
});
it('should open file metadata dialog when new diagram is saved', () => {
const saveFileChangesSpy = spyOn(component, 'saveFileChanges').and.stub();
const editFileMetaSpy = spyOn(component, 'editFileMeta').and.stub();
component.diagramComponent.writeValue('<xml>newValue</xml>');
component.saveChanges();
expect(saveFileChangesSpy).not.toHaveBeenCalled();
expect(editFileMetaSpy).toHaveBeenCalled();
});
it('should save file changes', () => {
const apiUpdateFileSpy = spyOn(component.api, 'updateFileMeta').and.returnValue(of(mockFileMeta0));
component.workflowSpec = mockWorkflowSpec0;
component.diagramFileMeta = mockFileMeta0;
component.diagramComponent.writeValue('<xml>newValue</xml>');
component.saveFileChanges();
expect(apiUpdateFileSpy).toHaveBeenCalledWith(mockWorkflowSpec0.id, mockFileMeta0);
});
it('should open file metadata dialog');
});

View File

@ -1,13 +1,13 @@
import {DatePipe} from '@angular/common';
import {AfterViewInit, Component, ViewChild} from '@angular/core';
import {MatDialog, MatDialogRef} from '@angular/material/dialog';
import {MatDialog} from '@angular/material/dialog';
import {MatSnackBar} from '@angular/material/snack-bar';
import {FileMeta, FileType, WorkflowSpec, ApiService} from 'sartography-workflow-lib';
import {ApiService, FileMeta, FileType, WorkflowSpec} from 'sartography-workflow-lib';
import {BpmnWarning} from './_interfaces/bpmn-warning';
import {FileMetaDialogData} from './_interfaces/file-meta-dialog-data';
import {ImportEvent} from './_interfaces/import-event';
import {NewFileDialogData} from './_interfaces/new-file-dialog-data';
import {DiagramComponent} from './diagram/diagram.component';
import {NewFileDialogComponent} from './new-file-dialog/new-file-dialog.component';
import {FileMetaDialogComponent} from './file-meta-dialog/file-meta-dialog.component';
@Component({
selector: 'app-root',
@ -43,10 +43,6 @@ export class AppComponent implements AfterViewInit {
this.diagramComponent.registerOnChange((newXmlValue: string) => {
this.draftXml = newXmlValue;
});
this.diagramComponent.registerOnTouched(() => {
console.log('diagramComponent onTouch');
});
}
handleImported(event: ImportEvent) {
@ -111,15 +107,11 @@ export class AppComponent implements AfterViewInit {
saveChanges() {
if (this.hasChanged()) {
console.log('saveChanges this.diagramFileMeta', this.diagramFileMeta);
if (this.diagramFileMeta && this.diagramFileMeta.workflow_spec_id) {
this.xml = this.draftXml;
this.diagramFileMeta.file = new File([this.xml], this.diagramFileMeta.name, {type: 'text/xml'});
this.api.updateFileMeta(this.workflowSpec.id, this.diagramFileMeta).subscribe(() => {
this.snackBar.open('Saved changes.', 'Ok', {duration: 5000});
});
// Save changes to just the file
this.saveFileChanges();
} else {
// Open the File Meta Dialog
this.editFileMeta();
}
}
@ -153,9 +145,11 @@ export class AppComponent implements AfterViewInit {
this.bpmnFiles = [];
files.forEach(f => {
this.api.getFileData(f.id).subscribe(d => {
f.content_type = (f.type === FileType.SVG) ? 'image/svg+xml' : f.content_type = 'text/xml';
if (f.type === FileType.BPMN) {
f.content_type = 'text/xml';
f.file = new File([d], f.name, {type: f.content_type});
this.bpmnFiles.push(f);
}
});
});
});
@ -165,7 +159,7 @@ export class AppComponent implements AfterViewInit {
editFileMeta() {
// Open new filename/workflow spec dialog
const dialogRef = this.dialog.open(NewFileDialogComponent, {
const dialogRef = this.dialog.open(FileMetaDialogComponent, {
height: '400px',
width: '400px',
data: {
@ -176,15 +170,14 @@ export class AppComponent implements AfterViewInit {
},
});
dialogRef.afterClosed().subscribe((data: NewFileDialogData) => {
console.log('dialog afterClosed result', data);
dialogRef.afterClosed().subscribe((data: FileMetaDialogData) => {
if (data && data.fileName && data.workflowSpecId) {
this._upsertSpecAndFileMeta(data);
}
});
}
private _upsertSpecAndFileMeta(data: NewFileDialogData) {
private _upsertSpecAndFileMeta(data: FileMetaDialogData) {
if (data.fileName && data.workflowSpecId) {
this.xml = this.draftXml;
@ -273,4 +266,12 @@ export class AppComponent implements AfterViewInit {
file.name.slice(-5) === '.bpmn' ||
file.name.slice(-4) === '.xml';
}
private saveFileChanges() {
this.xml = this.draftXml;
this.diagramFileMeta.file = new File([this.xml], this.diagramFileMeta.name, {type: 'text/xml'});
this.api.updateFileMeta(this.workflowSpec.id, this.diagramFileMeta).subscribe(() => {
this.snackBar.open('Saved changes to file.', 'Ok', {duration: 5000});
});
}
}

View File

@ -18,7 +18,7 @@ import {AppEnvironment} from 'sartography-workflow-lib';
import {environment} from '../environments/environment';
import {AppComponent} from './app.component';
import {DiagramComponent} from './diagram/diagram.component';
import { NewFileDialogComponent } from './new-file-dialog/new-file-dialog.component';
import { FileMetaDialogComponent } from './file-meta-dialog/file-meta-dialog.component';
class ThisEnvironment implements AppEnvironment {
production = environment.production;
@ -31,7 +31,7 @@ class ThisEnvironment implements AppEnvironment {
declarations: [
AppComponent,
DiagramComponent,
NewFileDialogComponent
FileMetaDialogComponent
],
imports: [
BrowserAnimationsModule,
@ -52,7 +52,7 @@ class ThisEnvironment implements AppEnvironment {
MatTooltipModule,
],
bootstrap: [AppComponent],
entryComponents: [NewFileDialogComponent],
entryComponents: [FileMetaDialogComponent],
providers: [{provide: 'APP_ENVIRONMENT', useClass: ThisEnvironment}]
})
export class AppModule {

View File

@ -0,0 +1,110 @@
import {async, ComponentFixture, TestBed} from '@angular/core/testing';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import {MAT_DIALOG_DATA, MatDialogModule, MatDialogRef} from '@angular/material/dialog';
import {MatFormFieldModule} from '@angular/material/form-field';
import {MatInputModule} from '@angular/material/input';
import {BrowserAnimationsModule, NoopAnimationsModule} from '@angular/platform-browser/animations';
import {FileMetaDialogData} from '../_interfaces/file-meta-dialog-data';
import {FileMetaDialogComponent} from './file-meta-dialog.component';
describe('EditFileMetaDialogComponent', () => {
let component: FileMetaDialogComponent;
let fixture: ComponentFixture<FileMetaDialogComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [FileMetaDialogComponent],
imports: [
BrowserAnimationsModule,
FormsModule,
MatDialogModule,
MatFormFieldModule,
MatInputModule,
NoopAnimationsModule,
ReactiveFormsModule,
],
providers: [
{
provide: MatDialogRef,
useValue: {
close: (dialogResult: any) => {
}
}
},
{provide: MAT_DIALOG_DATA, useValue: []},
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(FileMetaDialogComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should save data on submit', () => {
const closeSpy = spyOn(component.dialogRef, 'close').and.stub();
const dataBefore: FileMetaDialogData = {
fileName: 'green_eggs.bpmn',
workflowSpecId: 'green_eggs',
displayName: 'Green Eggs',
description: 'Eat them! Eat them! Here they are.',
};
component.data = dataBefore;
component.onSubmit();
expect(closeSpy).toHaveBeenCalledWith(dataBefore);
});
it('should not change data on cancel', () => {
const closeSpy = spyOn(component.dialogRef, 'close').and.stub();
const dataBefore: FileMetaDialogData = {
fileName: 'and_ham.bpmn',
workflowSpecId: 'and_ham',
displayName: 'And Ham',
description: 'Would you, could you, in a box?',
};
component.data = dataBefore;
component.onNoClick();
expect(closeSpy).toHaveBeenCalledWith();
});
it('should clean up filename', () => {
const closeSpy = spyOn(component.dialogRef, 'close').and.stub();
const dataBefore: FileMetaDialogData = {
fileName: ' 🍳 green_eggs.v1-2020-01-01.XML.bmnp 🍖 ',
workflowSpecId: 'green_eggs',
displayName: 'Green Eggs',
description: 'Eat them! Eat them! Here they are.',
};
component.data = dataBefore;
component.onSubmit();
const expectedData: FileMetaDialogData = JSON.parse(JSON.stringify(dataBefore));
expectedData.fileName = 'green_eggs.v1-2020-01-01.XML.bpmn';
expect(closeSpy).toHaveBeenCalledWith(expectedData);
});
it('should clean up workflow spec id', () => {
const closeSpy = spyOn(component.dialogRef, 'close').and.stub();
const dataBefore: FileMetaDialogData = {
fileName: 'green_eggs.bpmn',
workflowSpecId: ' 🍳 Green Eggs & Ham: A Dish Best Served Cold? 🍖 ',
displayName: 'Green Eggs',
description: 'I would not, could not, with a fox!',
};
component.data = dataBefore;
component.onSubmit();
const expectedData: FileMetaDialogData = JSON.parse(JSON.stringify(dataBefore));
expectedData.workflowSpecId = 'green_eggs_ham_a_dish_best_served_cold';
expect(closeSpy).toHaveBeenCalledWith(dataBefore);
});
});

View File

@ -0,0 +1,29 @@
import {Component, Inject} from '@angular/core';
import {MAT_DIALOG_DATA, MatDialogRef} from '@angular/material/dialog';
import {FileMetaDialogData} from '../_interfaces/file-meta-dialog-data';
import {cleanUpFilename, toSnakeCase, trimString} from '../_util/string-clean';
@Component({
selector: 'app-new-file-dialog',
templateUrl: './file-meta-dialog.component.html',
styleUrls: ['./file-meta-dialog.component.scss']
})
export class FileMetaDialogComponent {
constructor(
public dialogRef: MatDialogRef<FileMetaDialogComponent>,
@Inject(MAT_DIALOG_DATA) public data: FileMetaDialogData
) {
}
onNoClick() {
this.dialogRef.close();
}
onSubmit() {
this.data.workflowSpecId = toSnakeCase(this.data.workflowSpecId);
this.data.fileName = cleanUpFilename(this.data.fileName, 'bpmn');
this.dialogRef.close(this.data);
}
}

View File

@ -1,49 +0,0 @@
import {async, ComponentFixture, TestBed} from '@angular/core/testing';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import {MAT_DIALOG_DATA, MatDialogModule, MatDialogRef} from '@angular/material/dialog';
import {MatFormFieldModule} from '@angular/material/form-field';
import {MatInputModule} from '@angular/material/input';
import {BrowserAnimationsModule, NoopAnimationsModule} from '@angular/platform-browser/animations';
import {NewFileDialogComponent} from './new-file-dialog.component';
describe('NewFileDialogComponent', () => {
let component: NewFileDialogComponent;
let fixture: ComponentFixture<NewFileDialogComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [NewFileDialogComponent],
imports: [
BrowserAnimationsModule,
FormsModule,
MatDialogModule,
MatFormFieldModule,
MatInputModule,
NoopAnimationsModule,
ReactiveFormsModule,
],
providers: [
{
provide: MatDialogRef,
useValue: {
close: (dialogResult: any) => {
}
}
},
{provide: MAT_DIALOG_DATA, useValue: []},
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(NewFileDialogComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -1,41 +0,0 @@
import {Component, Inject} from '@angular/core';
import {MAT_DIALOG_DATA, MatDialogRef} from '@angular/material/dialog';
import {NewFileDialogData} from '../_interfaces/new-file-dialog-data';
import {toSnakeCase} from '../_util/snake-case';
@Component({
selector: 'app-new-file-dialog',
templateUrl: './new-file-dialog.component.html',
styleUrls: ['./new-file-dialog.component.scss']
})
export class NewFileDialogComponent {
constructor(
public dialogRef: MatDialogRef<NewFileDialogComponent>,
@Inject(MAT_DIALOG_DATA) public data: NewFileDialogData
) {
}
onNoClick() {
this.dialogRef.close(this.data);
}
onSubmit() {
this.data.workflowSpecId = toSnakeCase(this.data.workflowSpecId);
this.data.fileName = this._cleanUpFilename(this.data.fileName);
this.dialogRef.close(this.data);
}
private _cleanUpFilename(old: string): string {
const arr = old.trim().split('.');
// Add file extension, if necessary
if (arr.length < 2) {
arr.push('bpmn');
} else {
(arr[arr.length - 1]) = 'bpmn';
}
return arr.join('.');
}
}