[AAE-12501] Align JS API (#8344)

* [AAE-12501] Provide an AlfrescoApiService implementation that disable the AlfrescoApi oauth initialization when we use new oidc implementation

* [AAE-12501] Replace oauth2Auth with authentication service, define get username as abstract

* [AAE-12501] Replace sitesService with authentication service since sitesService get the username from oauth2Auth

* [AAE-12501] Call implicitLogin by authentication service

* [AAE-12501] Replace Oauth2Auth with AlfrescoApi and call the custom api without using authentication

* [AAE-12501] Replace oauth2Auth with authentication service to get the token

* [AAE-12501] Replace oauth2Auth with alfrescoApi

* remove unneeded JS-API dep
move auth in the right place

* [AAE-10501] Rename alfresco-api.http-client to adf-http-client

* [AAE-10501] Remove config from a CoreModule, a different service is provided in AuthModule to use angular http client instead of super agent

* [AAE-10501] Disable AlfrescoApi oauth initialization while using new adf oidc authentication

* [AAE-12501] Replace alfresco api client with AdfHttpClient

* [AAE-12501] Restore get username methods

* [AAE-12501] Get username with authentication service

* [AAE-12501] removee unused method

* [AAE-12501] Trigger on login when token is received

* [AAE-12501] Fix content-services unit test

* [AAE-12501] Fix import

* [AAE-12501] Fix core unit tests

* [AAE-12501] Fix process-services-cloud unit tests

* [AAE-12501] Create a request options interface with the needed props, remove the import from js-api, return the body from request

* [AAE-12501] Fix process-services-cloud unit tests without Expectation

* [AAE-12501] Fix Core secondary entrypoints unit tests are not executed: move test.ts one level up in order to find all the spec files into the secondary entrypoints folders and update path

* [AAE-12501] Fix Core unit tests that weren't executed because of the previous test.ts wrong location

* [AAE-12501] Fix authentication token_issued subscription

* add emitters

* [AAE-12501] Replace Math.random() to fix hospot security issue, fix lint issues

* [AAE-12501] Install event-emitter dependency

* [AAE-12501] Comment temporary setCsrfToken because is not possible to import app config service from core due to circular dependencies

* [AAE-12501] Get disableCsrf from app config serviice when app configuration is loaded

* [AAE-12501] Fix license-header lint issue

* [AAE-14221] Regenerate lock file

* [AAE-14221] Fix sonarcloud issues

* [AAE-12501] Remove wrong character

* [AAE-12501] Regenerate lock file

* [AAE-12501] Fix BC: update alfresco api response error

---------

Co-authored-by: eromano <eugenioromano16@gmail.com>
This commit is contained in:
Amedeo Lepore
2023-06-27 17:22:30 +02:00
committed by GitHub
parent 037dce0ae7
commit 7abebf0652
53 changed files with 5474 additions and 10457 deletions

View File

@@ -24,20 +24,15 @@ import { fakeApplicationInstance, fakeApplicationInstanceWithEnvironment } from
import { ProcessServiceCloudTestingModule } from '../../testing/process-service-cloud.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { fakeEnvironmentList } from '../../common/mock/environment.mock';
import { AdfHttpClient } from '@alfresco/adf-core/api';
describe('AppsProcessCloudService', () => {
let service: AppsProcessCloudService;
let appConfigService: AppConfigService;
let apiService: AlfrescoApiService;
let adfHttpClient: AdfHttpClient;
const apiMock: any = {
oauth2Auth: {
callCustomApi: () => Promise.resolve({list : { entries: [ {entry: fakeApplicationInstance[0]}, {entry: fakeApplicationInstance[1]}] }})
},
isEcmLoggedIn: () => false,
reply: jasmine.createSpy('reply')
};
const apiMockResponse: any = Promise.resolve({list : { entries: [ {entry: fakeApplicationInstance[0]}, {entry: fakeApplicationInstance[1]}] }});
setupTestBed({
imports: [
@@ -52,8 +47,8 @@ describe('AppsProcessCloudService', () => {
});
beforeEach(() => {
apiService = TestBed.inject(AlfrescoApiService);
spyOn(apiService, 'getInstance').and.returnValue(apiMock);
adfHttpClient = TestBed.inject(AdfHttpClient);
spyOn(adfHttpClient, 'request').and.returnValue(apiMockResponse);
service = TestBed.inject(AppsProcessCloudService);
appConfigService = TestBed.inject(AppConfigService);

View File

@@ -18,10 +18,11 @@
import { Injectable } from '@angular/core';
import { Observable, from, throwError, of } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { AlfrescoApiService, AppConfigService, LogService } from '@alfresco/adf-core';
import { Oauth2Auth } from '@alfresco/js-api';
import { AppConfigService, LogService } from '@alfresco/adf-core';
import { ApplicationInstanceModel } from '../models/application-instance.model';
import { Environment } from '../../common/interface/environment.interface';
import { AdfHttpClient } from '@alfresco/adf-core/api';
import { RequestOptions } from '@alfresco/js-api';
@Injectable({ providedIn: 'root' })
export class AppsProcessCloudService {
@@ -29,7 +30,7 @@ export class AppsProcessCloudService {
deployedApps: ApplicationInstanceModel[];
constructor(
private apiService: AlfrescoApiService,
private adfHttpClient: AdfHttpClient,
private logService: LogService,
private appConfigService: AppConfigService) {
this.loadApps();
@@ -73,18 +74,28 @@ export class AppsProcessCloudService {
if (status === '') {
return of([]);
}
const api: Oauth2Auth = this.apiService.getInstance().oauth2Auth;
const path = this.getApplicationUrl();
const pathParams = {};
const queryParams = { status, roles : role, sort: 'name' };
const httpMethod = 'GET';
const headerParams = {};
const formParams = {};
const bodyParam = {};
const contentTypes = ['application/json'];
const accepts = ['application/json'];
const requestOptions: RequestOptions = {
path,
pathParams,
queryParams,
headerParams,
formParams,
bodyParam,
contentTypes,
accepts,
httpMethod
};
return from(api.callCustomApi(path, 'GET', pathParams, queryParams, headerParams, formParams, bodyParam,
contentTypes, accepts))
return from(this.adfHttpClient.request(path, requestOptions))
.pipe(
map((applications: any) => applications.list.entries.map((application) => application.entry)),
catchError((err) => this.handleError(err))

View File

@@ -17,24 +17,24 @@
import { TestBed } from '@angular/core/testing';
import { FormCloudService } from './form-cloud.service';
import { AlfrescoApiService, setupTestBed } from '@alfresco/adf-core';
import { setupTestBed } from '@alfresco/adf-core';
import { of } from 'rxjs';
import { ProcessServiceCloudTestingModule } from '../../testing/process-service-cloud.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { AdfHttpClient } from '@alfresco/adf-core/api';
declare let jasmine: any;
const responseBody = {
const mockTaskResponseBody = {
entry:
{ id: 'id', name: 'name', formKey: 'form-key' }
};
const oauth2Auth = jasmine.createSpyObj('oauth2Auth', ['callCustomApi']);
const mockFormResponseBody = { formRepresentation: { id: 'form-id', name: 'task-form', taskId: 'task-id' } };
describe('Form Cloud service', () => {
let service: FormCloudService;
let apiService: AlfrescoApiService;
let adfHttpClient: AdfHttpClient;
let requestSpy: jasmine.Spy;
const appName = 'app-name';
const taskId = 'task-id';
const processInstanceId = 'process-instance-id';
@@ -48,26 +48,21 @@ describe('Form Cloud service', () => {
beforeEach(() => {
service = TestBed.inject(FormCloudService);
apiService = TestBed.inject(AlfrescoApiService);
spyOn(apiService, 'getInstance').and.returnValue({
oauth2Auth,
isEcmLoggedIn: () => false,
reply: jasmine.createSpy('reply')
} as any);
adfHttpClient = TestBed.inject(AdfHttpClient);
requestSpy = spyOn(adfHttpClient, 'request');
});
describe('Form tests', () => {
it('should fetch and parse form', (done) => {
const formId = 'form-id';
oauth2Auth.callCustomApi.and.returnValue(Promise.resolve({ formRepresentation: { id: formId, name: 'task-form', taskId: 'task-id' } }));
requestSpy.and.returnValue(Promise.resolve(mockFormResponseBody));
service.getForm(appName, formId).subscribe((result) => {
expect(result).toBeDefined();
expect(result.formRepresentation.id).toBe(formId);
expect(result.formRepresentation.name).toBe('task-form');
expect(oauth2Auth.callCustomApi.calls.mostRecent().args[0].endsWith(`${appName}/form/v1/forms/${formId}`)).toBeTruthy();
expect(oauth2Auth.callCustomApi.calls.mostRecent().args[1]).toBe('GET');
expect(requestSpy.calls.mostRecent().args[0]).toContain(`${appName}/form/v1/forms/${formId}`);
expect(requestSpy.calls.mostRecent().args[1].httpMethod).toBe('GET');
done();
});
});
@@ -85,101 +80,101 @@ describe('Form Cloud service', () => {
describe('Task tests', () => {
it('should fetch and parse task', (done) => {
oauth2Auth.callCustomApi.and.returnValue(Promise.resolve(responseBody));
requestSpy.and.returnValue(Promise.resolve(mockTaskResponseBody));
service.getTask(appName, taskId).subscribe((result) => {
expect(result).toBeDefined();
expect(result.id).toBe(responseBody.entry.id);
expect(result.name).toBe(responseBody.entry.name);
expect(oauth2Auth.callCustomApi.calls.mostRecent().args[0].endsWith(`${appName}/query/v1/tasks/${taskId}`)).toBeTruthy();
expect(oauth2Auth.callCustomApi.calls.mostRecent().args[1]).toBe('GET');
expect(result.id).toBe('id');
expect(result.name).toBe('name');
expect(requestSpy.calls.mostRecent().args[0]).toContain(`${appName}/query/v1/tasks/${taskId}`);
expect(requestSpy.calls.mostRecent().args[1].httpMethod).toBe('GET');
done();
});
});
it('should fetch task variables', (done) => {
oauth2Auth.callCustomApi.and.returnValue(Promise.resolve({
requestSpy.and.returnValue(Promise.resolve({
list: {
entries: [
{
entry: {
serviceName: 'fake-rb',
serviceFullName: 'fake-rb',
serviceVersion: '',
appName: 'fake',
appVersion: '',
serviceType: null,
id: 25,
type: 'string',
name: 'fakeProperty',
createTime: 1556112661342,
lastUpdatedTime: 1556112661342,
executionId: null,
value: 'fakeValue',
markedAsDeleted: false,
processInstanceId: '18e16bc7-6694-11e9-9c1b-0a586460028a',
taskId: '18e192da-6694-11e9-9c1b-0a586460028a',
taskVariable: true
}
entries: [
{
entry: {
serviceName: 'fake-rb',
serviceFullName: 'fake-rb',
serviceVersion: '',
appName: 'fake',
appVersion: '',
serviceType: null,
id: 25,
type: 'string',
name: 'fakeProperty',
createTime: 1556112661342,
lastUpdatedTime: 1556112661342,
executionId: null,
value: 'fakeValue',
markedAsDeleted: false,
processInstanceId: '18e16bc7-6694-11e9-9c1b-0a586460028a',
taskId: '18e192da-6694-11e9-9c1b-0a586460028a',
taskVariable: true
}
}
],
pagination: {
skipCount: 0,
maxItems: 100,
count: 1,
hasMoreItems: false,
totalItems: 1
}
],
pagination: {
skipCount: 0,
maxItems: 100,
count: 1,
hasMoreItems: false,
totalItems: 1
}
}
}));
}));
service.getTaskVariables(appName, taskId).subscribe((result) => {
expect(result).toBeDefined();
expect(result.length).toBe(1);
expect(result[0].name).toBe('fakeProperty');
expect(result[0].value).toBe('fakeValue');
expect(oauth2Auth.callCustomApi.calls.mostRecent().args[0].endsWith(`${appName}/query/v1/tasks/${taskId}/variables`)).toBeTruthy();
expect(oauth2Auth.callCustomApi.calls.mostRecent().args[1]).toBe('GET');
expect(requestSpy.calls.mostRecent().args[0]).toContain(`${appName}/query/v1/tasks/${taskId}/variables`);
expect(requestSpy.calls.mostRecent().args[1].httpMethod).toBe('GET');
done();
});
});
it('should fetch result if the variable value is 0', (done) => {
oauth2Auth.callCustomApi.and.returnValue(Promise.resolve({
requestSpy.and.returnValue(Promise.resolve({
list: {
entries: [
{
entry: {
serviceName: 'fake-rb',
serviceFullName: 'fake-rb',
serviceVersion: '',
appName: 'fake',
appVersion: '',
serviceType: null,
id: 25,
type: 'string',
name: 'fakeProperty',
createTime: 1556112661342,
lastUpdatedTime: 1556112661342,
executionId: null,
value: 0,
markedAsDeleted: false,
processInstanceId: '18e16bc7-6694-11e9-9c1b-0a586460028a',
taskId: '18e192da-6694-11e9-9c1b-0a586460028a',
taskVariable: true
}
entries: [
{
entry: {
serviceName: 'fake-rb',
serviceFullName: 'fake-rb',
serviceVersion: '',
appName: 'fake',
appVersion: '',
serviceType: null,
id: 25,
type: 'string',
name: 'fakeProperty',
createTime: 1556112661342,
lastUpdatedTime: 1556112661342,
executionId: null,
value: 0,
markedAsDeleted: false,
processInstanceId: '18e16bc7-6694-11e9-9c1b-0a586460028a',
taskId: '18e192da-6694-11e9-9c1b-0a586460028a',
taskVariable: true
}
}
],
pagination: {
skipCount: 0,
maxItems: 100,
count: 1,
hasMoreItems: false,
totalItems: 1
}
],
pagination: {
skipCount: 0,
maxItems: 100,
count: 1,
hasMoreItems: false,
totalItems: 1
}
}
}));
}));
service.getTaskVariables(appName, taskId).subscribe((result) => {
expect(result).toBeDefined();
@@ -191,7 +186,7 @@ describe('Form Cloud service', () => {
});
it('should fetch task form flattened', (done) => {
spyOn(service, 'getTask').and.returnValue(of(responseBody.entry));
spyOn(service, 'getTask').and.returnValue(of(mockTaskResponseBody.entry));
spyOn(service, 'getForm').and.returnValue(of({
formRepresentation: {
name: 'task-form',
@@ -202,40 +197,40 @@ describe('Form Cloud service', () => {
service.getTaskForm(appName, taskId).subscribe((result) => {
expect(result).toBeDefined();
expect(result.name).toBe('task-form');
expect(result.taskId).toBe(responseBody.entry.id);
expect(result.taskName).toBe(responseBody.entry.name);
expect(result.taskId).toBe('id');
expect(result.taskName).toBe('name');
done();
});
});
it('should save task form', (done) => {
oauth2Auth.callCustomApi.and.returnValue(Promise.resolve(responseBody));
requestSpy.and.returnValue(Promise.resolve(mockTaskResponseBody));
const formId = 'form-id';
service.saveTaskForm(appName, taskId, processInstanceId, formId, {}).subscribe((result: any) => {
expect(result).toBeDefined();
expect(result.id).toBe('id');
expect(result.name).toBe('name');
expect(oauth2Auth.callCustomApi.calls.mostRecent().args[0].endsWith(`${appName}/form/v1/forms/${formId}/save`)).toBeTruthy();
expect(oauth2Auth.callCustomApi.calls.mostRecent().args[1]).toBe('POST');
expect(requestSpy.calls.mostRecent().args[0]).toContain(`${appName}/form/v1/forms/${formId}/save`);
expect(requestSpy.calls.mostRecent().args[1].httpMethod).toBe('POST');
done();
});
});
it('should complete task form', (done) => {
oauth2Auth.callCustomApi.and.returnValue(Promise.resolve(responseBody));
requestSpy.and.returnValue(Promise.resolve(mockTaskResponseBody));
const formId = 'form-id';
service.completeTaskForm(appName, taskId, processInstanceId, formId, {}, '', 1).subscribe((result: any) => {
expect(result).toBeDefined();
expect(result.id).toBe('id');
expect(result.name).toBe('name');
expect(oauth2Auth.callCustomApi.calls.mostRecent().args[0].endsWith(`${appName}/form/v1/forms/${formId}/submit/versions/1`)).toBeTruthy();
expect(oauth2Auth.callCustomApi.calls.mostRecent().args[1]).toBe('POST');
expect(requestSpy.calls.mostRecent().args[0]).toContain(`${appName}/form/v1/forms/${formId}/submit/versions/1`);
expect(requestSpy.calls.mostRecent().args[1].httpMethod).toBe('POST');
done();
});
});
});
});
});

View File

@@ -25,6 +25,7 @@ import { TaskVariableCloud } from '../models/task-variable-cloud.model';
import { BaseCloudService } from '../../services/base-cloud.service';
import { FormContent } from '../../services/form-fields.interfaces';
import { FormCloudServiceInterface } from './form-cloud.service.interface';
import { AdfHttpClient } from '@alfresco/adf-core/api';
@Injectable({
providedIn: 'root'
@@ -37,8 +38,10 @@ export class FormCloudService extends BaseCloudService implements FormCloudServi
return this._uploadApi;
}
constructor() {
super();
constructor(
adfHttpClient: AdfHttpClient
) {
super(adfHttpClient);
}
/**

View File

@@ -16,20 +16,17 @@
*/
import { TestBed } from '@angular/core/testing';
import { AlfrescoApiService, setupTestBed } from '@alfresco/adf-core';
import { setupTestBed } from '@alfresco/adf-core';
import { FormDefinitionSelectorCloudService } from './form-definition-selector-cloud.service';
import { ProcessServiceCloudTestingModule } from '../../testing/process-service-cloud.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { mockFormRepresentations } from '../mocks/form-representation.mock';
declare let jasmine: any;
const oauth2Auth = jasmine.createSpyObj('oauth2Auth', ['callCustomApi', 'on']);
import { AdfHttpClient } from '@alfresco/adf-core/api';
describe('Form Definition Selector Cloud Service', () => {
let service: FormDefinitionSelectorCloudService;
let apiService: AlfrescoApiService;
let adfHttpClient: AdfHttpClient;
const appName = 'app-name';
setupTestBed({
@@ -41,17 +38,11 @@ describe('Form Definition Selector Cloud Service', () => {
beforeEach(() => {
service = TestBed.inject(FormDefinitionSelectorCloudService);
apiService = TestBed.inject(AlfrescoApiService);
spyOn(apiService, 'getInstance').and.returnValue({
oauth2Auth,
isEcmLoggedIn: () => false,
reply: jasmine.createSpy('reply')
} as any);
adfHttpClient = TestBed.inject(AdfHttpClient);
spyOn(adfHttpClient, 'request').and.returnValue(Promise.resolve(mockFormRepresentations));
});
it('should fetch all the forms when getForms is called', (done) => {
oauth2Auth.callCustomApi.and.returnValue(Promise.resolve(mockFormRepresentations));
service.getForms(appName).subscribe((result) => {
expect(result).toBeDefined();
expect(result.length).toBe(3);
@@ -60,8 +51,6 @@ describe('Form Definition Selector Cloud Service', () => {
});
it('should fetch only standalone enabled forms when getStandaloneTaskForms is called', (done) => {
oauth2Auth.callCustomApi.and.returnValue(Promise.resolve(mockFormRepresentations));
service.getStandAloneTaskForms(appName).subscribe((result) => {
expect(result).toBeDefined();
expect(result.length).toBe(2);

View File

@@ -16,8 +16,6 @@
*/
import { HttpErrorResponse } from '@angular/common/http';
import { throwError } from 'rxjs';
import { IdentityGroupModel } from '../models/identity-group.model';
import { IdentityGroupFilterInterface } from '../services/identity-group-filter.interface';
export const mockSearchGroupByRoles: IdentityGroupFilterInterface = {
@@ -35,23 +33,7 @@ export const mockSearchGroupByApp: IdentityGroupFilterInterface = {
withinApplication: 'fake-app-name'
};
export function oAuthMockApiWithIdentityGroups(groups: IdentityGroupModel[]) {
return {
oauth2Auth: {
callCustomApi: () => Promise.resolve(groups)
},
reply: jasmine.createSpy('reply')
};
}
const errorResponse = new HttpErrorResponse({
export const mockHttpErrorResponse = new HttpErrorResponse({
error: 'Mock Error',
status: 404, statusText: 'Not Found'
});
export const oAuthMockApiWithError = {
oauth2Auth: {
callCustomApi: () => throwError(errorResponse)
},
reply: jasmine.createSpy('reply')
};

View File

@@ -17,22 +17,23 @@
import { TestBed } from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core';
import { AlfrescoApiService, setupTestBed } from '@alfresco/adf-core';
import { setupTestBed } from '@alfresco/adf-core';
import { ProcessServiceCloudTestingModule } from '../../testing/process-service-cloud.testing.module';
import { IdentityGroupService } from './identity-group.service';
import {
mockHttpErrorResponse,
mockSearchGroupByApp,
mockSearchGroupByRoles,
mockSearchGroupByRolesAndApp,
oAuthMockApiWithError,
oAuthMockApiWithIdentityGroups
mockSearchGroupByRolesAndApp
} from '../mock/identity-group.service.mock';
import { mockFoodGroups } from '../mock/group-cloud.mock';
import { AdfHttpClient } from '@alfresco/adf-core/api';
describe('IdentityGroupService', () => {
let service: IdentityGroupService;
let alfrescoApiService: AlfrescoApiService;
let adfHttpClient: AdfHttpClient;
let requestSpy: jasmine.Spy;
setupTestBed({
imports: [
@@ -43,13 +44,14 @@ describe('IdentityGroupService', () => {
beforeEach(() => {
service = TestBed.inject(IdentityGroupService);
alfrescoApiService = TestBed.inject(AlfrescoApiService);
adfHttpClient = TestBed.inject(AdfHttpClient);
requestSpy = spyOn(adfHttpClient, 'request');
});
describe('Search', () => {
it('should fetch groups', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithIdentityGroups(mockFoodGroups )as any);
requestSpy.and.returnValue(Promise.resolve(mockFoodGroups));
const searchSpy = spyOn(service, 'search').and.callThrough();
service.search('fake').subscribe(
@@ -65,7 +67,7 @@ describe('IdentityGroupService', () => {
});
it('should not fetch groups if error occurred', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithError as any);
requestSpy.and.returnValue(Promise.reject(mockHttpErrorResponse));
const searchSpy = spyOn(service, 'search').and.callThrough();
@@ -85,7 +87,7 @@ describe('IdentityGroupService', () => {
});
it('should fetch groups by roles', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithIdentityGroups(mockFoodGroups) as any);
requestSpy.and.returnValue(Promise.resolve(mockFoodGroups));
const searchSpy = spyOn(service, 'search').and.callThrough();
service.search('fake', mockSearchGroupByRoles).subscribe(
@@ -102,7 +104,7 @@ describe('IdentityGroupService', () => {
});
it('should not fetch groups by roles if error occurred', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithError as any);
requestSpy.and.returnValue(Promise.reject(mockHttpErrorResponse));
const searchSpy = spyOn(service, 'search').and.callThrough();
service.search('fake', mockSearchGroupByRoles)
@@ -125,7 +127,7 @@ describe('IdentityGroupService', () => {
});
it('should fetch groups within app', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithIdentityGroups(mockFoodGroups) as any);
requestSpy.and.returnValue(Promise.resolve(mockFoodGroups));
service.search('fake', mockSearchGroupByApp).subscribe(
res => {
@@ -140,7 +142,7 @@ describe('IdentityGroupService', () => {
});
it('should fetch groups within app with roles', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithIdentityGroups(mockFoodGroups) as any);
requestSpy.and.returnValue(Promise.resolve(mockFoodGroups));
service.search('fake', mockSearchGroupByRolesAndApp).subscribe(
res => {
@@ -156,7 +158,7 @@ describe('IdentityGroupService', () => {
});
it('should not fetch groups within app if error occurred', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithError as any);
requestSpy.and.returnValue(Promise.reject(mockHttpErrorResponse));
const searchSpy = spyOn(service, 'search').and.callThrough();
service.search('fake', mockSearchGroupByApp)

View File

@@ -16,8 +16,6 @@
*/
import { HttpErrorResponse } from '@angular/common/http';
import { throwError } from 'rxjs';
import { IdentityUserModel } from '../models/identity-user.model';
import { IdentityUserFilterInterface } from '../services/identity-user-filter.interface';
export const mockSearchUserEmptyFilters: IdentityUserFilterInterface = {
@@ -68,23 +66,7 @@ export const mockSearchUserByAppAndGroups: IdentityUserFilterInterface = {
withinApplication: 'fake-app-name'
};
export function oAuthMockApiWithIdentityUsers(users: IdentityUserModel[]) {
return {
oauth2Auth: {
callCustomApi: () => Promise.resolve(users)
},
reply: jasmine.createSpy('reply')
} as any;
}
const errorResponse = new HttpErrorResponse({
export const mockHttpErrorResponse = new HttpErrorResponse({
error: 'Mock Error',
status: 404, statusText: 'Not Found'
});
export const oAuthMockApiWithError = {
oauth2Auth: {
callCustomApi: () => throwError(errorResponse)
},
reply: jasmine.createSpy('reply')
} as any;

View File

@@ -17,7 +17,7 @@
import { TestBed } from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core';
import { AlfrescoApiService, JwtHelperService, setupTestBed } from '@alfresco/adf-core';
import { JwtHelperService, setupTestBed } from '@alfresco/adf-core';
import { IdentityUserService } from './identity-user.service';
import { mockToken } from '../mock/jwt-helper.service.spec';
import { ProcessServiceCloudTestingModule } from '../../testing/process-service-cloud.testing.module';
@@ -28,16 +28,17 @@ import {
mockSearchUserByGroupsAndRoles,
mockSearchUserByGroupsAndRolesAndApp,
mockSearchUserByRoles,
mockSearchUserByRolesAndApp,
oAuthMockApiWithError,
oAuthMockApiWithIdentityUsers
mockSearchUserByRolesAndApp
} from '../mock/identity-user.service.mock';
import { mockFoodUsers } from '../mock/people-cloud.mock';
import { AdfHttpClient } from '@alfresco/adf-core/api';
import { mockHttpErrorResponse } from '../../group/mock/identity-group.service.mock';
describe('IdentityUserService', () => {
let service: IdentityUserService;
let alfrescoApiService: AlfrescoApiService;
let adfHttpClient: AdfHttpClient;
let requestSpy: jasmine.Spy;
setupTestBed({
imports: [
@@ -48,7 +49,8 @@ describe('IdentityUserService', () => {
beforeEach(() => {
service = TestBed.inject(IdentityUserService);
alfrescoApiService = TestBed.inject(AlfrescoApiService);
adfHttpClient = TestBed.inject(AdfHttpClient);
requestSpy = spyOn(adfHttpClient, 'request');
});
describe('Current user info (JWT token)', () => {
@@ -85,7 +87,7 @@ describe('IdentityUserService', () => {
describe('Search', () => {
it('should fetch users', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithIdentityUsers(mockFoodUsers));
requestSpy.and.returnValue(Promise.resolve(mockFoodUsers));
const searchSpy = spyOn(service, 'search').and.callThrough();
service.search('fake').subscribe(
@@ -101,7 +103,7 @@ describe('IdentityUserService', () => {
});
it('should not fetch users if error occurred', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithError as any);
requestSpy.and.returnValue(Promise.reject(mockHttpErrorResponse));
const searchSpy = spyOn(service, 'search').and.callThrough();
@@ -121,7 +123,7 @@ describe('IdentityUserService', () => {
});
it('should fetch users by roles', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithIdentityUsers(mockFoodUsers));
requestSpy.and.returnValue(Promise.resolve(mockFoodUsers));
const searchSpy = spyOn(service, 'search').and.callThrough();
service.search('fake', mockSearchUserByRoles).subscribe(
@@ -138,7 +140,7 @@ describe('IdentityUserService', () => {
});
it('should not fetch users by roles if error occurred', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithError);
requestSpy.and.returnValue(Promise.reject(mockHttpErrorResponse));
service.search('fake', mockSearchUserByRoles)
.subscribe(
@@ -155,7 +157,7 @@ describe('IdentityUserService', () => {
});
it('should fetch users by groups', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithIdentityUsers(mockFoodUsers));
requestSpy.and.returnValue(Promise.resolve(mockFoodUsers));
const searchSpy = spyOn(service, 'search').and.callThrough();
service.search('fake', mockSearchUserByGroups).subscribe(
@@ -172,7 +174,7 @@ describe('IdentityUserService', () => {
});
it('should fetch users by roles with groups', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithIdentityUsers(mockFoodUsers));
requestSpy.and.returnValue(Promise.resolve(mockFoodUsers));
const searchSpy = spyOn(service, 'search').and.callThrough();
service.search('fake', mockSearchUserByGroupsAndRoles).subscribe(
@@ -190,7 +192,7 @@ describe('IdentityUserService', () => {
});
it('should fetch users by roles with groups and appName', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithIdentityUsers(mockFoodUsers));
requestSpy.and.returnValue(Promise.resolve(mockFoodUsers));
const searchSpy = spyOn(service, 'search').and.callThrough();
service.search('fake', mockSearchUserByGroupsAndRolesAndApp).subscribe(
@@ -209,7 +211,7 @@ describe('IdentityUserService', () => {
});
it('should not fetch users by groups if error occurred', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithError);
requestSpy.and.returnValue(Promise.reject(mockHttpErrorResponse));
service.search('fake', mockSearchUserByGroups)
.subscribe(
@@ -226,7 +228,7 @@ describe('IdentityUserService', () => {
});
it('should fetch users within app', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithIdentityUsers(mockFoodUsers));
requestSpy.and.returnValue(Promise.resolve(mockFoodUsers));
service.search('fake', mockSearchUserByApp).subscribe(
res => {
@@ -241,7 +243,7 @@ describe('IdentityUserService', () => {
});
it('should fetch users within app with roles', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithIdentityUsers(mockFoodUsers));
requestSpy.and.returnValue(Promise.resolve(mockFoodUsers));
service.search('fake', mockSearchUserByRolesAndApp).subscribe(
res => {
@@ -257,7 +259,7 @@ describe('IdentityUserService', () => {
});
it('should fetch users within app with groups', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithIdentityUsers(mockFoodUsers));
requestSpy.and.returnValue(Promise.resolve(mockFoodUsers));
const searchSpy = spyOn(service, 'search').and.callThrough();
service.search('fake', mockSearchUserByAppAndGroups).subscribe(
@@ -275,7 +277,7 @@ describe('IdentityUserService', () => {
});
it('should not fetch users within app if error occurred', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithError);
requestSpy.and.returnValue(Promise.reject(mockHttpErrorResponse));
service.search('fake', mockSearchUserByApp)
.subscribe(

View File

@@ -16,42 +16,24 @@
*/
import { fakeAsync, TestBed } from '@angular/core/testing';
import { setupTestBed, AlfrescoApiService } from '@alfresco/adf-core';
import { setupTestBed } from '@alfresco/adf-core';
import { ProcessListCloudService } from './process-list-cloud.service';
import { ProcessQueryCloudRequestModel } from '../models/process-cloud-query-request.model';
import { ProcessServiceCloudTestingModule } from '../../../testing/process-service-cloud.testing.module';
import { AdfHttpClient } from '@alfresco/adf-core/api';
describe('ProcessListCloudService', () => {
let service: ProcessListCloudService;
let alfrescoApiService: AlfrescoApiService;
let adfHttpClient: AdfHttpClient;
let requestSpy: jasmine.Spy;
const returnCallQueryParameters = (): any => ({
oauth2Auth: {
callCustomApi: (_queryUrl, _operation, _context, queryParams) => Promise.resolve(queryParams)
},
isEcmLoggedIn: () => false
});
const returnCallQueryParameters = (_queryUrl, options) => Promise.resolve(options.queryParams);
const returnCallUrl = (): any => ({
oauth2Auth: {
callCustomApi: (queryUrl) => Promise.resolve(queryUrl)
},
isEcmLoggedIn: () => false
});
const returnCallUrl = (queryUrl) => Promise.resolve(queryUrl);
const returnCallOperation = (): any => ({
oauth2Auth: {
callCustomApi: (_queryUrl, operation, _context, _queryParams) => Promise.resolve(operation)
},
isEcmLoggedIn: () => false
});
const returnCallOperation = (_queryUrl, options) => Promise.resolve(options);
const returnCallBody = (): any => ({
oauth2Auth: {
callCustomApi: (_queryUrl, _operation, _context, _queryParams, _headerParams, _formParams, bodyParam) => Promise.resolve(bodyParam)
},
isEcmLoggedIn: () => false
});
const returnCallBody = (_queryUrl, options) => Promise.resolve(options.bodyParam);
setupTestBed({
imports: [
@@ -60,13 +42,14 @@ describe('ProcessListCloudService', () => {
});
beforeEach(fakeAsync(() => {
alfrescoApiService = TestBed.inject(AlfrescoApiService);
adfHttpClient = TestBed.inject(AdfHttpClient);
service = TestBed.inject(ProcessListCloudService);
requestSpy = spyOn(adfHttpClient, 'request');
}));
it('should append to the call all the parameters', (done) => {
const processRequest = { appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service' } as ProcessQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallQueryParameters);
requestSpy.and.callFake(returnCallQueryParameters);
service.getProcessByRequest(processRequest).subscribe((res) => {
expect(res).toBeDefined();
expect(res).not.toBeNull();
@@ -79,7 +62,7 @@ describe('ProcessListCloudService', () => {
it('should concat the app name to the request url', (done) => {
const processRequest = { appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service' } as ProcessQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallUrl);
requestSpy.and.callFake(returnCallUrl);
service.getProcessByRequest(processRequest).subscribe((requestUrl) => {
expect(requestUrl).toBeDefined();
expect(requestUrl).not.toBeNull();
@@ -93,7 +76,7 @@ describe('ProcessListCloudService', () => {
appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service',
sorting: [{ orderBy: 'NAME', direction: 'DESC' }, { orderBy: 'TITLE', direction: 'ASC' }]
} as ProcessQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallQueryParameters);
requestSpy.and.callFake(returnCallQueryParameters);
service.getProcessByRequest(processRequest).subscribe((res) => {
expect(res).toBeDefined();
expect(res).not.toBeNull();
@@ -104,7 +87,7 @@ describe('ProcessListCloudService', () => {
it('should return an error when app name is not specified', (done) => {
const processRequest = { appName: null } as ProcessQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallUrl);
requestSpy.and.callFake(returnCallUrl);
service.getProcessByRequest(processRequest).subscribe(
() => { },
(error) => {
@@ -118,7 +101,7 @@ describe('ProcessListCloudService', () => {
it('should append to the call all the parameters', async () => {
const processRequest = { appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service' } as ProcessQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallQueryParameters);
requestSpy.and.callFake(returnCallQueryParameters);
const request = await service.getAdminProcessByRequest(processRequest).toPromise();
expect(request).toBeDefined();
@@ -130,7 +113,7 @@ describe('ProcessListCloudService', () => {
it('should concat the app name to the request url', async () => {
const processRequest = { appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service' } as ProcessQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallUrl);
requestSpy.and.callFake(returnCallUrl);
const requestUrl = await service.getAdminProcessByRequest(processRequest).toPromise();
expect(requestUrl).toBeDefined();
@@ -143,7 +126,7 @@ describe('ProcessListCloudService', () => {
appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service',
sorting: [{ orderBy: 'NAME', direction: 'DESC' }, { orderBy: 'TITLE', direction: 'ASC' }]
} as ProcessQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallQueryParameters);
requestSpy.and.callFake(returnCallQueryParameters);
const request = await service.getAdminProcessByRequest(processRequest).toPromise();
expect(request).toBeDefined();
@@ -153,7 +136,7 @@ describe('ProcessListCloudService', () => {
it('should return an error when app name is not specified', async () => {
const processRequest = { appName: null } as ProcessQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallUrl);
requestSpy.and.callFake(returnCallUrl);
try {
await service.getAdminProcessByRequest(processRequest).toPromise();
@@ -166,16 +149,16 @@ describe('ProcessListCloudService', () => {
it('should make post request', async () => {
const processRequest = { appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service' } as ProcessQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallOperation);
const requestMethod = await service.getAdminProcessByRequest(processRequest).toPromise();
expect(requestMethod).toBeDefined();
expect(requestMethod).not.toBeNull();
expect(requestMethod).toBe('POST');
requestSpy.and.callFake(returnCallOperation);
const adminProcessResponse = await service.getAdminProcessByRequest(processRequest).toPromise();
expect(adminProcessResponse).toBeDefined();
expect(adminProcessResponse).not.toBeNull();
expect(adminProcessResponse.httpMethod).toBe('POST');
});
it('should not have variable keys as part of query parameters', async () => {
const processRequest = { appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service', variableKeys: ['test-one', 'test-two'] } as ProcessQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallQueryParameters);
requestSpy.and.callFake(returnCallQueryParameters);
const requestParams = await service.getAdminProcessByRequest(processRequest).toPromise();
expect(requestParams).toBeDefined();
@@ -185,7 +168,7 @@ describe('ProcessListCloudService', () => {
it('should send right variable keys as post body', async () => {
const processRequest = { appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service', variableKeys: ['test-one', 'test-two'] } as ProcessQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallBody);
requestSpy.and.callFake(returnCallBody);
const requestBodyParams = await service.getAdminProcessByRequest(processRequest).toPromise();
expect(requestBodyParams).toBeDefined();

View File

@@ -17,16 +17,17 @@
import { TestBed } from '@angular/core/testing';
import { of, throwError } from 'rxjs';
import { setupTestBed, AlfrescoApiService } from '@alfresco/adf-core';
import { setupTestBed } from '@alfresco/adf-core';
import { StartProcessCloudService } from './start-process-cloud.service';
import { fakeProcessPayload } from '../mock/start-process.component.mock';
import { ProcessDefinitionCloud } from '../../../models/process-definition-cloud.model';
import { HttpErrorResponse, HttpClientModule } from '@angular/common/http';
import { AdfHttpClient } from '@alfresco/adf-core/api';
describe('StartProcessCloudService', () => {
let service: StartProcessCloudService;
let alfrescoApiService: AlfrescoApiService;
let adfHttpClient: AdfHttpClient;
setupTestBed({
imports: [HttpClientModule]
@@ -34,7 +35,7 @@ describe('StartProcessCloudService', () => {
beforeEach(() => {
service = TestBed.inject(StartProcessCloudService);
alfrescoApiService = TestBed.inject(AlfrescoApiService);
adfHttpClient = TestBed.inject(AdfHttpClient);
});
it('should be able to create a new process', (done) => {
@@ -105,11 +106,8 @@ describe('StartProcessCloudService', () => {
it('should transform the response into task variables', (done) => {
const appName = 'test-app';
const processDefinitionId = 'processDefinitionId';
const oauth2Auth = jasmine.createSpyObj('oauth2Auth', ['callCustomApi']);
oauth2Auth.callCustomApi.and.returnValue(Promise.resolve({ static1: 'value', static2: 0, static3: true }));
spyOn(alfrescoApiService, 'getInstance').and.returnValue({
oauth2Auth
} as any);
const requestSpy = spyOn(adfHttpClient, 'request');
requestSpy.and.returnValue(Promise.resolve({ static1: 'value', static2: 0, static3: true }));
service.getStartEventFormStaticValuesMapping(appName, processDefinitionId).subscribe((result) => {
expect(result.length).toEqual(3);
@@ -122,8 +120,8 @@ describe('StartProcessCloudService', () => {
expect(result[2].name).toEqual('static3');
expect(result[2].id).toEqual('static3');
expect(result[2].value).toEqual(true);
expect(oauth2Auth.callCustomApi.calls.mostRecent().args[0].endsWith(`${appName}/rb/v1/process-definitions/${processDefinitionId}/static-values`)).toBeTruthy();
expect(oauth2Auth.callCustomApi.calls.mostRecent().args[1]).toBe('GET');
expect(requestSpy.calls.mostRecent().args[0]).toContain(`${appName}/rb/v1/process-definitions/${processDefinitionId}/static-values`);
expect(requestSpy.calls.mostRecent().args[1].httpMethod).toBe('GET');
done();
});
});

View File

@@ -18,35 +18,27 @@
import { AlfrescoApiService, AppConfigService, LogService } from '@alfresco/adf-core';
import { Injectable, inject } from '@angular/core';
import { from, Observable } from 'rxjs';
import { AdfHttpClient } from '@alfresco/adf-core/api';
import { RequestOptions } from '@alfresco/js-api';
export interface CallApiParams {
path: string;
httpMethod: string;
pathParams?: any;
queryParams?: any;
headerParams?: any;
formParams?: any;
bodyParam?: any;
contentTypes?: string[];
accepts?: string[];
returnType?: any;
contextRoot?: string;
responseType?: string;
}
@Injectable()
export class BaseCloudService {
protected apiService = inject(AlfrescoApiService);
protected appConfigService = inject(AppConfigService);
protected logService = inject(LogService);
protected defaultParams: CallApiParams = {
protected defaultParams: RequestOptions = {
path: '',
httpMethod: '',
contentTypes: ['application/json'],
accepts: ['application/json']
};
constructor(
protected adfHttpClient: AdfHttpClient) {}
getBasePath(appName: string): string {
return appName
? `${this.contextRoot}/${appName}`
@@ -55,63 +47,64 @@ export class BaseCloudService {
protected post<T, R>(url: string, data?: T, queryParams?: any): Observable<R> {
return from(
this.callApi<R>({
...this.defaultParams,
path: url,
httpMethod: 'POST',
bodyParam: data,
queryParams
})
this.callApi<R>(
url,
{
...this.defaultParams,
path: url,
httpMethod: 'POST',
bodyParam: data,
queryParams
}
)
);
}
protected put<T, R>(url: string, data?: T): Observable<R> {
return from(
this.callApi<R>({
...this.defaultParams,
path: url,
httpMethod: 'PUT',
bodyParam: data
})
this.callApi<R>(
url,
{
...this.defaultParams,
path: url,
httpMethod: 'PUT',
bodyParam: data
}
)
);
}
protected delete(url: string): Observable<void> {
return from(
this.callApi<void>({
...this.defaultParams,
path: url,
httpMethod: 'DELETE'
})
this.callApi<void>(
url,
{
...this.defaultParams,
path: url,
httpMethod: 'DELETE'
}
)
);
}
protected get<T>(url: string, queryParams?: any): Observable<T> {
return from(
this.callApi<T>({
...this.defaultParams,
path: url,
httpMethod: 'GET',
queryParams
})
this.callApi<T>(
url,
{
...this.defaultParams,
path: url,
httpMethod: 'GET',
queryParams
}
)
);
}
protected callApi<T>(params: CallApiParams): Promise<T> {
return this.apiService.getInstance()
.oauth2Auth.callCustomApi(
params.path,
params.httpMethod,
params.pathParams,
params.queryParams,
params.headerParams,
params.formParams,
params.bodyParam,
params.contentTypes,
params.accepts,
params.returnType,
params.contextRoot,
params.responseType
protected callApi<T>(url: string, params: RequestOptions): Promise<T> {
return this.adfHttpClient.request(
url,
params
);
}

View File

@@ -16,7 +16,7 @@
*/
import { TestBed } from '@angular/core/testing';
import { AlfrescoApiService, setupTestBed } from '@alfresco/adf-core';
import { setupTestBed } from '@alfresco/adf-core';
import { ProcessServiceCloudTestingModule } from '../testing/process-service-cloud.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { NotificationCloudService } from './notification-cloud.service';
@@ -27,7 +27,7 @@ describe('NotificationCloudService', () => {
let apollo: Apollo;
let apolloCreateSpy: jasmine.Spy;
let apolloSubscribeSpy: jasmine.Spy;
let apiService: AlfrescoApiService;
const useMock: any = {
subscribe: () => {}
};
@@ -43,14 +43,6 @@ describe('NotificationCloudService', () => {
}
`;
const apiServiceMock: any = {
oauth2Auth: {
token: '1234567'
},
isEcmLoggedIn: () => false,
reply: jasmine.createSpy('reply')
};
setupTestBed({
imports: [
TranslateModule.forRoot(),
@@ -61,9 +53,7 @@ describe('NotificationCloudService', () => {
beforeEach(() => {
service = TestBed.inject(NotificationCloudService);
apollo = TestBed.inject(Apollo);
apiService = TestBed.inject(AlfrescoApiService);
spyOn(apiService, 'getInstance').and.returnValue(apiServiceMock);
service.appsListening = [];
apolloCreateSpy = spyOn(apollo, 'createNamed');
apolloSubscribeSpy = spyOn(apollo, 'use').and.returnValue(useMock);

View File

@@ -22,7 +22,9 @@ import { WebSocketLink } from '@apollo/client/link/ws';
import { onError } from '@apollo/client/link/error';
import { getMainDefinition } from '@apollo/client/utilities';
import { Injectable } from '@angular/core';
import { AuthenticationService } from '@alfresco/adf-core';
import { BaseCloudService } from './base-cloud.service';
import { AdfHttpClient } from '@alfresco/adf-core/api';
@Injectable({
providedIn: 'root'
@@ -30,8 +32,12 @@ import { BaseCloudService } from './base-cloud.service';
export class NotificationCloudService extends BaseCloudService {
appsListening = [];
constructor(public apollo: Apollo, private http: HttpLink) {
super();
constructor(
public apollo: Apollo,
private http: HttpLink,
private authService: AuthenticationService,
protected adfHttpClient: AdfHttpClient) {
super(adfHttpClient);
}
private get webSocketHost() {
@@ -57,7 +63,7 @@ export class NotificationCloudService extends BaseCloudService {
connectionParams: {
kaInterval: 2000,
// eslint-disable-next-line @typescript-eslint/naming-convention
'X-Authorization': 'Bearer ' + this.apiService.getInstance().oauth2Auth.token
'X-Authorization': 'Bearer ' + this.authService.getToken()
}
}
});
@@ -81,7 +87,7 @@ export class NotificationCloudService extends BaseCloudService {
headers: {
...oldHeaders,
// eslint-disable-next-line @typescript-eslint/naming-convention
'X-Authorization': 'Bearer ' + this.apiService.getInstance().oauth2Auth.token
'X-Authorization': 'Bearer ' + this.authService.getToken()
}
});
forward(operation);

View File

@@ -17,36 +17,22 @@
import { TestBed } from '@angular/core/testing';
import { UserPreferenceCloudService } from './user-preference-cloud.service';
import { setupTestBed, AlfrescoApiService } from '@alfresco/adf-core';
import { setupTestBed } from '@alfresco/adf-core';
import { mockPreferences, getMockPreference, createMockPreference, updateMockPreference } from '../mock/user-preference.mock';
import { ProcessServiceCloudTestingModule } from '../testing/process-service-cloud.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { AdfHttpClient } from '@alfresco/adf-core/api';
describe('PreferenceService', () => {
let service: UserPreferenceCloudService;
let alfrescoApiMock: AlfrescoApiService;
let getInstanceSpy: jasmine.Spy;
let adfHttpClient: AdfHttpClient;
let requestSpy: jasmine.Spy;
const errorResponse = {
error: 'Mock Error',
state: 404, stateText: 'Not Found'
};
const apiMock = (mockResponse): any => ({
oauth2Auth: {
callCustomApi: () => Promise.resolve(mockResponse)
},
isEcmLoggedIn: () => false,
reply: jasmine.createSpy('reply')
});
const apiErrorMock: any = {
oauth2Auth: {
callCustomApi: () => Promise.reject(errorResponse)
},
isEcmLoggedIn:() => false
};
setupTestBed({
imports: [
TranslateModule.forRoot(),
@@ -56,8 +42,8 @@ describe('PreferenceService', () => {
beforeEach(() => {
service = TestBed.inject(UserPreferenceCloudService);
alfrescoApiMock = TestBed.inject(AlfrescoApiService);
getInstanceSpy = spyOn(alfrescoApiMock, 'getInstance').and.returnValue(apiMock(mockPreferences));
adfHttpClient = TestBed.inject(AdfHttpClient);
requestSpy = spyOn(adfHttpClient, 'request').and.returnValue(Promise.resolve(mockPreferences));
});
it('should return the preferences', (done) => {
@@ -81,7 +67,7 @@ describe('PreferenceService', () => {
});
it('Should not fetch preferences if error occurred', (done) => {
getInstanceSpy.and.returnValue(apiErrorMock);
requestSpy.and.returnValue(Promise.reject(errorResponse));
service.getPreferences('mock-app-name')
.subscribe(
() => fail('expected an error, not preferences'),
@@ -95,7 +81,7 @@ describe('PreferenceService', () => {
});
it('should return the preference by key', (done) => {
getInstanceSpy.and.returnValue(apiMock(getMockPreference));
requestSpy.and.returnValue(Promise.resolve(getMockPreference));
service.getPreferenceByKey('mock-app-name', 'mock-preference-key').subscribe((res: any) => {
expect(res).toBeDefined();
expect(res).not.toBeNull();
@@ -109,7 +95,7 @@ describe('PreferenceService', () => {
});
it('Should not fetch preference by key if error occurred', (done) => {
getInstanceSpy.and.returnValue(apiErrorMock);
requestSpy.and.returnValue(Promise.reject(errorResponse));
service.getPreferenceByKey('mock-app-name', 'mock-preference-key')
.subscribe(
() => fail('expected an error, not preference'),
@@ -123,7 +109,7 @@ describe('PreferenceService', () => {
});
it('should create preference', (done) => {
getInstanceSpy.and.returnValue(apiMock(createMockPreference));
requestSpy.and.returnValue(Promise.resolve(createMockPreference));
service.createPreference('mock-app-name', 'mock-preference-key', createMockPreference).subscribe((res: any) => {
expect(res).toBeDefined();
expect(res).not.toBeNull();
@@ -135,7 +121,7 @@ describe('PreferenceService', () => {
});
it('Should not create preference if error occurred', (done) => {
getInstanceSpy.and.returnValue(apiErrorMock);
requestSpy.and.returnValue(Promise.reject(errorResponse));
service.createPreference('mock-app-name', 'mock-preference-key', createMockPreference)
.subscribe(
() => fail('expected an error, not to create preference'),
@@ -149,7 +135,7 @@ describe('PreferenceService', () => {
});
it('should update preference', (done) => {
getInstanceSpy.and.returnValue(apiMock(updateMockPreference));
requestSpy.and.returnValue(Promise.resolve(updateMockPreference));
service.updatePreference('mock-app-name', 'mock-preference-key', updateMockPreference).subscribe((res: any) => {
expect(res).toBeDefined();
expect(res).not.toBeNull();
@@ -161,7 +147,7 @@ describe('PreferenceService', () => {
});
it('Should not update preference if error occurred', (done) => {
getInstanceSpy.and.returnValue(apiErrorMock);
requestSpy.and.returnValue(Promise.reject(errorResponse));
service.createPreference('mock-app-name', 'mock-preference-key', updateMockPreference)
.subscribe(
() => fail('expected an error, not to update preference'),
@@ -175,7 +161,7 @@ describe('PreferenceService', () => {
});
it('should delete preference', (done) => {
getInstanceSpy.and.returnValue(apiMock(''));
requestSpy.and.returnValue(Promise.resolve(''));
service.deletePreference('mock-app-name', 'mock-preference-key').subscribe((res: any) => {
expect(res).toBeDefined();
done();
@@ -183,7 +169,7 @@ describe('PreferenceService', () => {
});
it('Should not delete preference if error occurred', (done) => {
getInstanceSpy.and.returnValue(apiErrorMock);
requestSpy.and.returnValue(Promise.reject(errorResponse));
service.deletePreference('mock-app-name', 'mock-preference-key')
.subscribe(
() => fail('expected an error, not to delete preference'),

View File

@@ -16,7 +16,7 @@
*/
import { TestBed } from '@angular/core/testing';
import { setupTestBed, TranslationService, AlfrescoApiService } from '@alfresco/adf-core';
import { setupTestBed, TranslationService } from '@alfresco/adf-core';
import { TaskCloudService } from './task-cloud.service';
import { taskCompleteCloudMock } from '../task-header/mocks/fake-complete-task.mock';
import { assignedTaskDetailsCloudMock, createdTaskDetailsCloudMock, emptyOwnerTaskDetailsCloudMock } from '../task-header/mocks/task-details-cloud.mock';
@@ -25,53 +25,25 @@ import { cloudMockUser } from '../start-task/mock/user-cloud.mock';
import { ProcessServiceCloudTestingModule } from '../../testing/process-service-cloud.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { IdentityUserService } from '../../people/services/identity-user.service';
import { AdfHttpClient } from '@alfresco/adf-core/api';
describe('Task Cloud Service', () => {
let service: TaskCloudService;
let alfrescoApiMock: AlfrescoApiService;
let adfHttpClient: AdfHttpClient;
let identityUserService: IdentityUserService;
let translateService: TranslationService;
let requestSpy: jasmine.Spy;
const returnFakeTaskCompleteResults = (): any => ({
reply: () => {},
oauth2Auth: {
callCustomApi : () => Promise.resolve(taskCompleteCloudMock)
},
isEcmLoggedIn: () => false
});
const returnFakeTaskCompleteResults = () => Promise.resolve(taskCompleteCloudMock);
const returnFakeTaskCompleteResultsError = (): any => ({
reply: () => {},
oauth2Auth: {
callCustomApi : () => Promise.reject(taskCompleteCloudMock)
},
isEcmLoggedIn: () => false
});
const returnFakeTaskCompleteResultsError = () => Promise.reject(taskCompleteCloudMock);
const returnFakeTaskDetailsResults = (): any => ({
reply: () => {},
oauth2Auth: {
callCustomApi : () => Promise.resolve(fakeTaskDetailsCloud)
},
isEcmLoggedIn: () => false
});
const returnFakeTaskDetailsResults = () => Promise.resolve(fakeTaskDetailsCloud);
const returnFakeCandidateUsersResults = (): any => ({
reply: () => {},
oauth2Auth: {
callCustomApi : () => Promise.resolve(['mockuser1', 'mockuser2', 'mockuser3'])
},
isEcmLoggedIn: () => false
});
const returnFakeCandidateUsersResults = () => Promise.resolve(['mockuser1', 'mockuser2', 'mockuser3']);
const returnFakeCandidateGroupResults = (): any => ({
reply: () => {},
oauth2Auth: {
callCustomApi : () => Promise.resolve(['mockgroup1', 'mockgroup2', 'mockgroup3'])
},
isEcmLoggedIn: () => false
});
const returnFakeCandidateGroupResults = () => Promise.resolve(['mockgroup1', 'mockgroup2', 'mockgroup3']);
setupTestBed({
imports: [
@@ -81,18 +53,19 @@ describe('Task Cloud Service', () => {
});
beforeEach(() => {
alfrescoApiMock = TestBed.inject(AlfrescoApiService);
adfHttpClient = TestBed.inject(AdfHttpClient);
identityUserService = TestBed.inject(IdentityUserService);
translateService = TestBed.inject(TranslationService);
service = TestBed.inject(TaskCloudService);
spyOn(translateService, 'instant').and.callFake((key) => key ? `${key}_translated` : null);
spyOn(identityUserService, 'getCurrentUserInfo').and.returnValue(cloudMockUser);
requestSpy = spyOn(adfHttpClient, 'request');
});
it('should complete a task', (done) => {
const appName = 'simple-app';
const taskId = '68d54a8f';
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskCompleteResults);
requestSpy.and.callFake(returnFakeTaskCompleteResults);
service.completeTask(appName, taskId).subscribe((res: any) => {
expect(res).toBeDefined();
expect(res).not.toBeNull();
@@ -103,7 +76,7 @@ describe('Task Cloud Service', () => {
});
it('should not complete a task', (done) => {
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskCompleteResultsError);
requestSpy.and.callFake(returnFakeTaskCompleteResultsError);
const appName = 'simple-app';
const taskId = '68d54a8f';
@@ -140,7 +113,7 @@ describe('Task Cloud Service', () => {
const appName = 'simple-app';
const taskId = '68d54a8f';
const canCompleteTaskResult = service.canCompleteTask(emptyOwnerTaskDetailsCloudMock);
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskCompleteResults);
requestSpy.and.callFake(returnFakeTaskCompleteResults);
service.completeTask(appName, taskId).subscribe((res: any) => {
expect(canCompleteTaskResult).toEqual(true);
@@ -156,7 +129,7 @@ describe('Task Cloud Service', () => {
const appName = 'taskp-app';
const assignee = 'user12';
const taskId = '68d54a8f';
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults);
requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.claimTask(appName, taskId, assignee).subscribe((res: any) => {
expect(res).toBeDefined();
expect(res).not.toBeNull();
@@ -170,7 +143,7 @@ describe('Task Cloud Service', () => {
const appName = null;
const taskId = '68d54a8f';
const assignee = 'user12';
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults);
requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.claimTask(appName, taskId, assignee).subscribe(
() => { },
(error) => {
@@ -183,7 +156,7 @@ describe('Task Cloud Service', () => {
const appName = 'task-app';
const taskId = null;
const assignee = 'user12';
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults);
requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.claimTask(appName, taskId, assignee).subscribe(
() => { },
(error) => {
@@ -195,7 +168,7 @@ describe('Task Cloud Service', () => {
it('should return the task details when unclaiming a task', (done) => {
const appName = 'taskp-app';
const taskId = '68d54a8f';
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults);
requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.unclaimTask(appName, taskId).subscribe((res: any) => {
expect(res).toBeDefined();
expect(res).not.toBeNull();
@@ -208,7 +181,7 @@ describe('Task Cloud Service', () => {
it('should throw error if appName is not defined when unclaiming a task', (done) => {
const appName = null;
const taskId = '68d54a8f';
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults);
requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.unclaimTask(appName, taskId).subscribe(
() => { },
(error) => {
@@ -220,7 +193,7 @@ describe('Task Cloud Service', () => {
it('should throw error if taskId is not defined when unclaiming a task', (done) => {
const appName = 'task-app';
const taskId = null;
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults);
requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.unclaimTask(appName, taskId).subscribe(
() => { },
(error) => {
@@ -232,7 +205,7 @@ describe('Task Cloud Service', () => {
it('should return the task details when querying by id', (done) => {
const appName = 'taskp-app';
const taskId = '68d54a8f';
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults);
requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.getTaskById(appName, taskId).subscribe((res: any) => {
expect(res).toBeDefined();
expect(res).not.toBeNull();
@@ -245,7 +218,7 @@ describe('Task Cloud Service', () => {
it('should throw error if appName is not defined when querying by id', (done) => {
const appName = null;
const taskId = '68d54a8f';
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults);
requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.getTaskById(appName, taskId).subscribe(
() => { },
(error) => {
@@ -257,7 +230,7 @@ describe('Task Cloud Service', () => {
it('should throw error if taskId is not defined when querying by id', (done) => {
const appName = 'task-app';
const taskId = null;
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults);
requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.getTaskById(appName, taskId).subscribe(
() => { },
(error) => {
@@ -270,7 +243,7 @@ describe('Task Cloud Service', () => {
const appName = null;
const taskId = '68d54a8f';
const updatePayload = { description: 'New description' };
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults);
requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.updateTask(appName, taskId, updatePayload).subscribe(
() => { },
(error) => {
@@ -283,7 +256,7 @@ describe('Task Cloud Service', () => {
const appName = 'task-app';
const taskId = null;
const updatePayload = { description: 'New description' };
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults);
requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.updateTask(appName, taskId, updatePayload).subscribe(
() => { },
(error) => {
@@ -296,7 +269,7 @@ describe('Task Cloud Service', () => {
const appName = 'taskp-app';
const taskId = '68d54a8f';
const updatePayload = { description: 'New description' };
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults);
requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.updateTask(appName, taskId, updatePayload).subscribe((res: any) => {
expect(res).toBeDefined();
expect(res).not.toBeNull();
@@ -310,7 +283,7 @@ describe('Task Cloud Service', () => {
const appName = null;
const taskId = '68d54a8f';
const updatePayload = { description: 'New description' };
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults);
requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.updateTask(appName, taskId, updatePayload).subscribe(
() => { },
(error) => {
@@ -323,7 +296,7 @@ describe('Task Cloud Service', () => {
const appName = 'task-app';
const taskId = null;
const updatePayload = { description: 'New description' };
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults);
requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.updateTask(appName, taskId, updatePayload).subscribe(
() => { },
(error) => {
@@ -335,7 +308,7 @@ describe('Task Cloud Service', () => {
it('should return the candidate users by appName and taskId', (done) => {
const appName = 'taskp-app';
const taskId = '68d54a8f';
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeCandidateUsersResults);
requestSpy.and.callFake(returnFakeCandidateUsersResults);
service.getCandidateUsers(appName, taskId).subscribe((res: string[]) => {
expect(res).toBeDefined();
expect(res).not.toBeNull();
@@ -349,7 +322,7 @@ describe('Task Cloud Service', () => {
it('should log message and return empty array if appName is not defined when fetching candidate users', (done) => {
const appName = null;
const taskId = '68d54a8f';
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeCandidateUsersResults);
requestSpy.and.callFake(returnFakeCandidateUsersResults);
service.getCandidateUsers(appName, taskId).subscribe(
(res: any[]) => {
expect(res.length).toBe(0);
@@ -360,7 +333,7 @@ describe('Task Cloud Service', () => {
it('should log message and return empty array if taskId is not defined when fetching candidate users', (done) => {
const appName = 'task-app';
const taskId = null;
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeCandidateUsersResults);
requestSpy.and.callFake(returnFakeCandidateUsersResults);
service.getCandidateUsers(appName, taskId).subscribe(
(res: any[]) => {
expect(res.length).toBe(0);
@@ -371,7 +344,7 @@ describe('Task Cloud Service', () => {
it('should return the candidate groups by appName and taskId', (done) => {
const appName = 'taskp-app';
const taskId = '68d54a8f';
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeCandidateGroupResults);
requestSpy.and.callFake(returnFakeCandidateGroupResults);
service.getCandidateGroups(appName, taskId).subscribe((res: string[]) => {
expect(res).toBeDefined();
expect(res).not.toBeNull();
@@ -385,7 +358,7 @@ describe('Task Cloud Service', () => {
it('should log message and return empty array if appName is not defined when fetching candidate groups', (done) => {
const appName = null;
const taskId = '68d54a8f';
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeCandidateGroupResults);
requestSpy.and.callFake(returnFakeCandidateGroupResults);
service.getCandidateGroups(appName, taskId).subscribe(
(res: any[]) => {
expect(res.length).toBe(0);
@@ -396,7 +369,7 @@ describe('Task Cloud Service', () => {
it('should log message and return empty array if taskId is not defined when fetching candidate groups', (done) => {
const appName = 'task-app';
const taskId = null;
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeCandidateGroupResults);
requestSpy.and.callFake(returnFakeCandidateGroupResults);
service.getCandidateGroups(appName, taskId).subscribe(
(res: any[]) => {
expect(res.length).toBe(0);
@@ -407,7 +380,7 @@ describe('Task Cloud Service', () => {
it('should call assign api and return updated task details', (done) => {
const appName = 'task-app';
const taskId = '68d54a8f';
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults);
requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.assign(appName, taskId, 'Phil Woods').subscribe(
(res) => {
expect(res.assignee).toBe('Phil Woods');
@@ -418,7 +391,7 @@ describe('Task Cloud Service', () => {
it('should throw error if appName is not defined when changing task assignee', (done) => {
const appName = '';
const taskId = '68d54a8f';
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults);
requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.assign(appName, taskId, 'mock-assignee').subscribe(
() => { },
(error) => {
@@ -430,7 +403,7 @@ describe('Task Cloud Service', () => {
it('should throw error if taskId is not defined when changing task assignee', (done) => {
const appName = 'task-app';
const taskId = '';
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults);
requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.assign(appName, taskId, 'mock-assignee').subscribe(
() => { },
(error) => {

View File

@@ -33,6 +33,7 @@ import { ProcessDefinitionCloud } from '../../models/process-definition-cloud.mo
import { DEFAULT_TASK_PRIORITIES, TaskPriorityOption } from '../models/task.model';
import { TaskCloudServiceInterface } from './task-cloud.service.interface';
import { IdentityUserService } from '../../people/services/identity-user.service';
import { AdfHttpClient } from '@alfresco/adf-core/api';
@Injectable({
providedIn: 'root'
@@ -43,9 +44,10 @@ export class TaskCloudService extends BaseCloudService implements TaskCloudServi
constructor(
private translateService: TranslationService,
private identityUserService: IdentityUserService
private identityUserService: IdentityUserService,
adfHttpClient: AdfHttpClient
) {
super();
super(adfHttpClient);
}
/**

View File

@@ -26,6 +26,7 @@ import { TaskCloudNodePaging } from '../../../models/task-cloud.model';
import { NotificationCloudService } from '../../../services/notification-cloud.service';
import { TaskCloudEngineEvent } from '../../../models/engine-event-cloud.model';
import { IdentityUserService } from '../../../people/services/identity-user.service';
import { AdfHttpClient } from '@alfresco/adf-core/api';
const TASK_EVENT_SUBSCRIPTION_QUERY = `
subscription {
@@ -54,8 +55,9 @@ export class TaskFilterCloudService extends BaseCloudService {
private identityUserService: IdentityUserService,
@Inject(TASK_FILTERS_SERVICE_TOKEN)
public preferenceService: PreferenceCloudServiceInterface,
private notificationCloudService: NotificationCloudService) {
super();
private notificationCloudService: NotificationCloudService,
adfHttpClient: AdfHttpClient) {
super(adfHttpClient);
this.filtersSubject = new BehaviorSubject([]);
this.filters$ = this.filtersSubject.asObservable();
}

View File

@@ -296,6 +296,7 @@ describe('TaskFormCloudComponent', () => {
spyOn(component.cancelClick,'emit').and.stub();
fixture.detectChanges();
const cancelBtn = debugElement.query(By.css('#adf-cloud-cancel-task'));
cancelBtn.triggerEventHandler('click', {});
fixture.detectChanges();
@@ -347,7 +348,7 @@ describe('TaskFormCloudComponent', () => {
expect(component.error.emit).toHaveBeenCalled();
});
it('should reload when task is completed', () => {
it('should reload when task is completed', async () => {
spyOn(taskCloudService, 'completeTask').and.returnValue(of({}));
const reloadSpy = spyOn(component, 'ngOnChanges').and.callThrough();
@@ -356,10 +357,11 @@ describe('TaskFormCloudComponent', () => {
const completeBtn = debugElement.query(By.css('[adf-cloud-complete-task]'));
completeBtn.nativeElement.click();
await fixture.whenStable();
expect(reloadSpy).toHaveBeenCalled();
});
it('should reload when task is claimed', () => {
it('should reload when task is claimed', async () => {
spyOn(taskCloudService, 'claimTask').and.returnValue(of({}));
spyOn(component, 'hasCandidateUsers').and.returnValue(true);
const reloadSpy = spyOn(component, 'ngOnChanges').and.callThrough();
@@ -372,10 +374,11 @@ describe('TaskFormCloudComponent', () => {
const claimBtn = debugElement.query(By.css('[adf-cloud-claim-task]'));
claimBtn.nativeElement.click();
await fixture.whenStable();
expect(reloadSpy).toHaveBeenCalled();
});
it('should emit taskUnclaimed when task is unclaimed', () => {
it('should emit taskUnclaimed when task is unclaimed', async () => {
spyOn(taskCloudService, 'unclaimTask').and.returnValue(of({}));
const reloadSpy = spyOn(component, 'ngOnChanges').and.callThrough();
spyOn(component, 'hasCandidateUsers').and.returnValue(true);
@@ -389,6 +392,7 @@ describe('TaskFormCloudComponent', () => {
const unclaimBtn = debugElement.query(By.css('[adf-cloud-unclaim-task]'));
unclaimBtn.nativeElement.click();
await fixture.whenStable();
expect(reloadSpy).toHaveBeenCalled();
});

View File

@@ -16,32 +16,23 @@
*/
import { TestBed } from '@angular/core/testing';
import { setupTestBed, AlfrescoApiService, LogService } from '@alfresco/adf-core';
import { setupTestBed, LogService } from '@alfresco/adf-core';
import { ServiceTaskListCloudService } from './service-task-list-cloud.service';
import { ServiceTaskQueryCloudRequestModel } from '../models/service-task-cloud.model';
import { ProcessServiceCloudTestingModule } from '../../../testing/process-service-cloud.testing.module';
import { of } from 'rxjs';
import { AdfHttpClient } from '@alfresco/adf-core/api';
describe('Activiti ServiceTaskList Cloud Service', () => {
let service: ServiceTaskListCloudService;
let alfrescoApiService: AlfrescoApiService;
let adfHttpClient: AdfHttpClient;
let logService: LogService;
let requestSpy: jasmine.Spy;
const returnCallQueryParameters = (): any => ({
oauth2Auth: {
callCustomApi: (_queryUrl, _operation, _context, queryParams) => Promise.resolve(queryParams)
},
isEcmLoggedIn: () => false,
reply: jasmine.createSpy('reply')
});
const returnCallQueryParameters = (_queryUrl, options) => Promise.resolve(options.queryParams);
const returnCallUrl = (): any => ({
oauth2Auth: {
callCustomApi: (queryUrl) => Promise.resolve(queryUrl)
},
isEcmLoggedIn: () => false
});
const returnCallUrl = (queryUrl) => Promise.resolve(queryUrl);
setupTestBed({
imports: [
@@ -50,14 +41,15 @@ describe('Activiti ServiceTaskList Cloud Service', () => {
});
beforeEach(() => {
alfrescoApiService = TestBed.inject(AlfrescoApiService);
adfHttpClient = TestBed.inject(AdfHttpClient);
service = TestBed.inject(ServiceTaskListCloudService);
logService = TestBed.inject(LogService);
requestSpy = spyOn(adfHttpClient, 'request');
});
it('should append to the call all the parameters', (done) => {
const taskRequest = { appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service' } as ServiceTaskQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallQueryParameters);
requestSpy.and.callFake(returnCallQueryParameters);
service.getServiceTaskByRequest(taskRequest).subscribe((res) => {
expect(res).toBeDefined();
expect(res).not.toBeNull();
@@ -70,7 +62,7 @@ describe('Activiti ServiceTaskList Cloud Service', () => {
it('should concat the app name to the request url', (done) => {
const taskRequest = { appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service' } as ServiceTaskQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallUrl);
requestSpy.and.callFake(returnCallUrl);
service.getServiceTaskByRequest(taskRequest).subscribe((requestUrl) => {
expect(requestUrl).toBeDefined();
expect(requestUrl).not.toBeNull();
@@ -84,7 +76,7 @@ describe('Activiti ServiceTaskList Cloud Service', () => {
appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service',
sorting: [{ orderBy: 'NAME', direction: 'DESC' }, { orderBy: 'TITLE', direction: 'ASC' }]
} as ServiceTaskQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallQueryParameters);
requestSpy.and.callFake(returnCallQueryParameters);
service.getServiceTaskByRequest(taskRequest).subscribe((res) => {
expect(res).toBeDefined();
expect(res).not.toBeNull();
@@ -95,7 +87,7 @@ describe('Activiti ServiceTaskList Cloud Service', () => {
it('should return an error when app name is not specified', (done) => {
const taskRequest = { appName: null } as ServiceTaskQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallUrl);
requestSpy.and.callFake(returnCallUrl);
service.getServiceTaskByRequest(taskRequest).subscribe(
() => { },
(error) => {
@@ -111,7 +103,7 @@ describe('Activiti ServiceTaskList Cloud Service', () => {
beforeEach(() => {
spyOn(service, 'getBasePath').and.returnValue('http://localhost/fakeName');
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallUrl);
requestSpy.and.callFake(returnCallUrl);
logServiceErrorSpy = spyOn(logService, 'error');
});

View File

@@ -16,31 +16,22 @@
*/
import { TestBed } from '@angular/core/testing';
import { setupTestBed, AlfrescoApiService } from '@alfresco/adf-core';
import { setupTestBed } from '@alfresco/adf-core';
import { TaskListCloudService } from './task-list-cloud.service';
import { TaskQueryCloudRequestModel } from '../../../models/filter-cloud-model';
import { ProcessServiceCloudTestingModule } from '../../../testing/process-service-cloud.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { AdfHttpClient } from '@alfresco/adf-core/api';
describe('TaskListCloudService', () => {
let service: TaskListCloudService;
let alfrescoApiService: AlfrescoApiService;
let adfHttpClient: AdfHttpClient;
let requestSpy: jasmine.Spy;
const returnCallQueryParameters = (): any => ({
oauth2Auth: {
callCustomApi : (_queryUrl, _operation, _context, queryParams) => Promise.resolve(queryParams)
},
isEcmLoggedIn: () => false,
reply: jasmine.createSpy('reply')
});
const returnCallQueryParameters = (_queryUrl, options) => Promise.resolve(options.queryParams);
const returnCallUrl = (): any => ({
oauth2Auth: {
callCustomApi : (queryUrl) => Promise.resolve(queryUrl)
},
isEcmLoggedIn: () => false
});
const returnCallUrl = (queryUrl) => Promise.resolve(queryUrl);
setupTestBed({
imports: [
@@ -50,13 +41,14 @@ describe('TaskListCloudService', () => {
});
beforeEach(() => {
alfrescoApiService = TestBed.inject(AlfrescoApiService);
adfHttpClient = TestBed.inject(AdfHttpClient);
service = TestBed.inject(TaskListCloudService);
requestSpy = spyOn(adfHttpClient, 'request');
});
it('should append to the call all the parameters', (done) => {
const taskRequest = { appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service' } as TaskQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallQueryParameters);
requestSpy.and.callFake(returnCallQueryParameters);
service.getTaskByRequest(taskRequest).subscribe((res) => {
expect(res).toBeDefined();
expect(res).not.toBeNull();
@@ -69,7 +61,7 @@ describe('TaskListCloudService', () => {
it('should concat the app name to the request url', (done) => {
const taskRequest = { appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service' } as TaskQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallUrl);
requestSpy.and.callFake(returnCallUrl);
service.getTaskByRequest(taskRequest).subscribe((requestUrl) => {
expect(requestUrl).toBeDefined();
expect(requestUrl).not.toBeNull();
@@ -81,7 +73,7 @@ describe('TaskListCloudService', () => {
it('should concat the sorting to append as parameters', (done) => {
const taskRequest = { appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service',
sorting: [{ orderBy: 'NAME', direction: 'DESC'}, { orderBy: 'TITLE', direction: 'ASC'}] } as TaskQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallQueryParameters);
requestSpy.and.callFake(returnCallQueryParameters);
service.getTaskByRequest(taskRequest).subscribe((res) => {
expect(res).toBeDefined();
expect(res).not.toBeNull();
@@ -92,7 +84,7 @@ describe('TaskListCloudService', () => {
it('should return an error when app name is not specified', (done) => {
const taskRequest = { appName: null } as TaskQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallUrl);
requestSpy.and.callFake(returnCallUrl);
service.getTaskByRequest(taskRequest).subscribe(
() => { },
(error) => {