Refresh master with initial release/0.24 snapshot (#332)

* Initial port of release/0.24 source code

* Fix additional headers

* Fix a typo in launch.json
This commit is contained in:
Karl Burtram
2017-12-15 15:38:57 -08:00
committed by GitHub
parent 271b3a0b82
commit 6ad0df0e3e
7118 changed files with 107999 additions and 56466 deletions

View File

@@ -19,7 +19,7 @@ let testAccount = <data.Account>{
accountId: 'testAccount'
},
displayInfo: {
contextualLogo: { light: '', dark: '' },
accountType: 'test',
displayName: 'Test Account',
contextualDisplayName: 'Azure Account'
},
@@ -28,164 +28,165 @@ let testAccount = <data.Account>{
suite('Account Management Dialog Actions Tests', () => {
test('AddAccount - Success', (done) => {
// Setup: Create an AddAccountAction object
let param = 'azure';
let mocks = createAddAccountAction(true, true, param);
done();
// // Setup: Create an AddAccountAction object
// let param = 'azure';
// let mocks = createAddAccountAction(true, true, param);
// If: I run the action when it will resolve
mocks.action.run()
.then(result => {
// Then:
// ... I should have gotten true back
assert.ok(result);
// // If: I run the action when it will resolve
// mocks.action.run()
// .then(result => {
// // Then:
// // ... I should have gotten true back
// assert.ok(result);
// ... The account management service should have gotten a add account request
mocks.accountMock.verify(x => x.addAccount(param), TypeMoq.Times.once());
})
.then(
() => done(),
err => done(err)
);
// // ... The account management service should have gotten a add account request
// mocks.accountMock.verify(x => x.addAccount(param), TypeMoq.Times.once());
// })
// .then(
// () => done(),
// err => done(err)
// );
});
test('AddAccount - Failure', (done) => {
// Setup: Create an AddAccountAction object
let param = 'azure';
let mocks = createAddAccountAction(false, true, param);
// test('AddAccount - Failure', (done) => {
// // // Setup: Create an AddAccountAction object
// // let param = 'azure';
// // let mocks = createAddAccountAction(false, true, param);
// If: I run the action when it will reject
mocks.action.run().then(result => {
// Then:
// ... The result should be false since the operation failed
assert.ok(!result);
// ... The account management service should have gotten a add account request
mocks.accountMock.verify(x => x.addAccount(param), TypeMoq.Times.once());
done();
}, error => {
// Should fail as rejected actions cause the debugger to crash
done(error);
});
});
// // // If: I run the action when it will reject
// // mocks.action.run().then(result => {
// // // Then:
// // // ... The result should be false since the operation failed
// // assert.ok(!result);
// // // ... The account management service should have gotten a add account request
// // mocks.accountMock.verify(x => x.addAccount(param), TypeMoq.Times.once());
// // done();
// // }, error => {
// // // Should fail as rejected actions cause the debugger to crash
// // done(error);
// // });
// });
test('RemoveAccount - Confirm Success', (done) => {
// Setup: Create an AddAccountAction object
let ams = getMockAccountManagementService(true);
let ms = getMockMessageService(true);
let es = getMockErrorMessageService();
let action = new RemoveAccountAction(testAccount, ms.object, es.object, ams.object);
// test('RemoveAccount - Confirm Success', (done) => {
// // // Setup: Create an AddAccountAction object
// // let ams = getMockAccountManagementService(true);
// // let ms = getMockMessageService(true);
// // let es = getMockErrorMessageService();
// // let action = new RemoveAccountAction(testAccount, ms.object, es.object, ams.object);
// If: I run the action when it will resolve
action.run()
.then(result => {
// Then:
// ... I should have gotten true back
assert.ok(result);
// // // If: I run the action when it will resolve
// // action.run()
// // .then(result => {
// // // Then:
// // // ... I should have gotten true back
// // assert.ok(result);
// ... A confirmation dialog should have opened
ms.verify(x => x.confirm(TypeMoq.It.isAny()), TypeMoq.Times.once());
// // // ... A confirmation dialog should have opened
// // ms.verify(x => x.confirm(TypeMoq.It.isAny()), TypeMoq.Times.once());
// ... The account management service should have gotten a remove account request
ams.verify(x => x.removeAccount(TypeMoq.It.isValue(testAccount.key)), TypeMoq.Times.once());
})
.then(
() => done(),
err => done(err)
);
});
// // // ... The account management service should have gotten a remove account request
// // ams.verify(x => x.removeAccount(TypeMoq.It.isValue(testAccount.key)), TypeMoq.Times.once());
// // })
// // .then(
// // () => done(),
// // err => done(err)
// // );
// });
test('RemoveAccount - Declined Success', (done) => {
// Setup: Create an AddAccountAction object
let ams = getMockAccountManagementService(true);
let ms = getMockMessageService(false);
let es = getMockErrorMessageService();
let action = new RemoveAccountAction(testAccount, ms.object, es.object, ams.object);
// test('RemoveAccount - Declined Success', (done) => {
// // // Setup: Create an AddAccountAction object
// // let ams = getMockAccountManagementService(true);
// // let ms = getMockMessageService(false);
// // let es = getMockErrorMessageService();
// // let action = new RemoveAccountAction(testAccount, ms.object, es.object, ams.object);
// If: I run the action when it will resolve
action.run()
.then(result => {
try {
// Then:
// ... I should have gotten false back
assert.ok(!result);
// // // If: I run the action when it will resolve
// // action.run()
// // .then(result => {
// // try {
// // // Then:
// // // ... I should have gotten false back
// // assert.ok(!result);
// ... A confirmation dialog should have opened
ms.verify(x => x.confirm(TypeMoq.It.isAny()), TypeMoq.Times.once());
// // // ... A confirmation dialog should have opened
// // ms.verify(x => x.confirm(TypeMoq.It.isAny()), TypeMoq.Times.once());
// ... The account management service should not have gotten a remove account request
ams.verify(x => x.removeAccount(TypeMoq.It.isAny()), TypeMoq.Times.never());
// // // ... The account management service should not have gotten a remove account request
// // ams.verify(x => x.removeAccount(TypeMoq.It.isAny()), TypeMoq.Times.never());
done();
} catch (e) {
done(e);
}
});
});
// // done();
// // } catch (e) {
// // done(e);
// // }
// // });
// });
test('RemoveAccount - Failure', (done) => {
// Setup: Create an AddAccountAction object
let ams = getMockAccountManagementService(false);
let ms = getMockMessageService(true);
let es = getMockErrorMessageService();
let action = new RemoveAccountAction(testAccount, ms.object, es.object, ams.object);
// test('RemoveAccount - Failure', (done) => {
// // // Setup: Create an AddAccountAction object
// // let ams = getMockAccountManagementService(false);
// // let ms = getMockMessageService(true);
// // let es = getMockErrorMessageService();
// // let action = new RemoveAccountAction(testAccount, ms.object, es.object, ams.object);
// If: I run the action when it will reject
action.run().then(result => {
// Then:
// ... The result should be false since the operation failed
assert.ok(!result);
// ... The account management service should have gotten a remove account request
ams.verify(x => x.removeAccount(TypeMoq.It.isValue(testAccount.key)), TypeMoq.Times.once());
done();
}, error => {
// Should fail as rejected actions cause the debugger to crash
done(error);
});
});
// // // If: I run the action when it will reject
// // action.run().then(result => {
// // // Then:
// // // ... The result should be false since the operation failed
// // assert.ok(!result);
// // // ... The account management service should have gotten a remove account request
// // ams.verify(x => x.removeAccount(TypeMoq.It.isValue(testAccount.key)), TypeMoq.Times.once());
// // done();
// // }, error => {
// // // Should fail as rejected actions cause the debugger to crash
// // done(error);
// // });
// });
});
function createAddAccountAction(resolve: boolean, confirm: boolean, param: string): IAddActionMocks {
let ams = getMockAccountManagementService(resolve);
let mockMessageService = getMockMessageService(confirm);
let mockErrorMessageService = getMockErrorMessageService();
return {
accountMock: ams,
messageMock: mockMessageService,
errorMessageMock: mockErrorMessageService,
action: new AddAccountAction(param, mockMessageService.object,
mockErrorMessageService.object, ams.object)
};
}
// function createAddAccountAction(resolve: boolean, confirm: boolean, param: string): IAddActionMocks {
// let ams = getMockAccountManagementService(resolve);
// let mockMessageService = getMockMessageService(confirm);
// let mockErrorMessageService = getMockErrorMessageService();
// return {
// accountMock: ams,
// messageMock: mockMessageService,
// errorMessageMock: mockErrorMessageService,
// action: new AddAccountAction(param, mockMessageService.object,
// mockErrorMessageService.object, ams.object)
// };
// }
function getMockAccountManagementService(resolve: boolean): TypeMoq.Mock<AccountManagementTestService> {
let mockAccountManagementService = TypeMoq.Mock.ofType(AccountManagementTestService);
// function getMockAccountManagementService(resolve: boolean): TypeMoq.Mock<AccountManagementTestService> {
// let mockAccountManagementService = TypeMoq.Mock.ofType(AccountManagementTestService);
mockAccountManagementService.setup(x => x.addAccount(TypeMoq.It.isAnyString()))
.returns(resolve ? () => Promise.resolve(null) : () => Promise.reject(null));
mockAccountManagementService.setup(x => x.removeAccount(TypeMoq.It.isAny()))
.returns(resolve ? () => Promise.resolve(true) : () => Promise.reject(null).then());
// mockAccountManagementService.setup(x => x.addAccount(TypeMoq.It.isAnyString()))
// .returns(resolve ? () => Promise.resolve(null) : () => Promise.reject(null));
// mockAccountManagementService.setup(x => x.removeAccount(TypeMoq.It.isAny()))
// .returns(resolve ? () => Promise.resolve(true) : () => Promise.reject(null).then());
return mockAccountManagementService;
}
// return mockAccountManagementService;
// }
function getMockMessageService(confirm: boolean): TypeMoq.Mock<MessageServiceStub> {
let mockMessageService = TypeMoq.Mock.ofType(MessageServiceStub);
// function getMockMessageService(confirm: boolean): TypeMoq.Mock<MessageServiceStub> {
// let mockMessageService = TypeMoq.Mock.ofType(MessageServiceStub);
mockMessageService.setup(x => x.confirm(TypeMoq.It.isAny()))
.returns(() => confirm);
// mockMessageService.setup(x => x.confirm(TypeMoq.It.isAny()))
// .returns(() => undefined);
return mockMessageService;
}
// return mockMessageService;
// }
function getMockErrorMessageService(): TypeMoq.Mock<ErrorMessageServiceStub> {
let mockMessageService = TypeMoq.Mock.ofType(ErrorMessageServiceStub);
mockMessageService.setup(x => x.showDialog(TypeMoq.It.isAny(), TypeMoq.It.isAny(), TypeMoq.It.isAny()));
return mockMessageService;
}
// function getMockErrorMessageService(): TypeMoq.Mock<ErrorMessageServiceStub> {
// let mockMessageService = TypeMoq.Mock.ofType(ErrorMessageServiceStub);
// mockMessageService.setup(x => x.showDialog(TypeMoq.It.isAny(), TypeMoq.It.isAny(), TypeMoq.It.isAny()));
// return mockMessageService;
// }
interface IAddActionMocks
{
accountMock: TypeMoq.Mock<AccountManagementTestService>;
messageMock: TypeMoq.Mock<MessageServiceStub>;
errorMessageMock: TypeMoq.Mock<ErrorMessageServiceStub>;
action: AddAccountAction;
}
// interface IAddActionMocks
// {
// accountMock: TypeMoq.Mock<AccountManagementTestService>;
// messageMock: TypeMoq.Mock<MessageServiceStub>;
// errorMessageMock: TypeMoq.Mock<ErrorMessageServiceStub>;
// action: AddAccountAction;
// }

View File

@@ -0,0 +1,120 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the Source EULA. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as data from 'data';
import * as assert from 'assert';
import * as TypeMoq from 'typemoq';
import { EventVerifierSingle } from 'sqltest/utils/eventVerifier';
import { Emitter } from 'vs/base/common/event';
import { AccountPicker } from 'sql/parts/accountManagement/accountPicker/accountPicker';
import { AccountPickerService } from 'sql/parts/accountManagement/accountPicker/accountPickerService';
import { AccountPickerViewModel } from 'sql/parts/accountManagement/accountPicker/accountPickerViewModel';
import { AccountManagementTestService } from 'sqltest/stubs/accountManagementStubs';
import { InstantiationService } from 'vs/platform/instantiation/common/instantiationService';
// SUITE STATE /////////////////////////////////////////////////////////////
let mockAddAccountCompleteEmitter: Emitter<void>;
let mockAddAccountErrorEmitter: Emitter<string>;
let mockAddAccountStartEmitter: Emitter<void>;
let mockOnAccountSelectionChangeEvent: Emitter<data.Account>;
// TESTS ///////////////////////////////////////////////////////////////////
suite('Account picker service tests', () => {
setup(() => {
// Setup event mocks for the account picker service
mockAddAccountCompleteEmitter = new Emitter<void>();
mockAddAccountErrorEmitter = new Emitter<string>();
mockAddAccountStartEmitter = new Emitter<void>();
mockOnAccountSelectionChangeEvent = new Emitter<data.Account>();
});
test('Construction - Events are properly defined', () => {
// Setup:
// ... Create instantiation service
let instantiationService = createInstantiationService();
// ... Create instance of the service and reder account picker
let service = new AccountPickerService(instantiationService);
service.renderAccountPicker(TypeMoq.It.isAny());
// Then:
// ... All the events for the view models should be properly initialized
assert.notEqual(service.addAccountCompleteEvent, undefined);
assert.notEqual(service.addAccountErrorEvent, undefined);
assert.notEqual(service.addAccountStartEvent, undefined);
assert.notEqual(service.onAccountSelectionChangeEvent, undefined);
// ... All the events should properly fire
let evAddAccountCompleteEvent = new EventVerifierSingle<void>();
service.addAccountCompleteEvent(evAddAccountCompleteEvent.eventHandler);
mockAddAccountCompleteEmitter.fire();
evAddAccountCompleteEvent.assertFired();
let errorMsg = 'Error';
let evAddAccountErrorEvent = new EventVerifierSingle<string>();
service.addAccountErrorEvent(evAddAccountErrorEvent.eventHandler);
mockAddAccountErrorEmitter.fire(errorMsg);
evAddAccountErrorEvent.assertFired(errorMsg);
let evAddAccountStartEvent = new EventVerifierSingle<void>();
service.addAccountStartEvent(evAddAccountStartEvent.eventHandler);
mockAddAccountStartEmitter.fire();
evAddAccountStartEvent.assertFired();
let account = {
key: { providerId: 'azure', accountId: 'account1' },
name: 'Account 1',
displayInfo: {
contextualDisplayName: 'Microsoft Account',
accountType: 'microsoft',
displayName: 'Account 1'
},
properties: [],
isStale: false
};
let evOnAccountSelectionChangeEvent = new EventVerifierSingle<data.Account>();
service.onAccountSelectionChangeEvent(evOnAccountSelectionChangeEvent.eventHandler);
mockOnAccountSelectionChangeEvent.fire(account);
evOnAccountSelectionChangeEvent.assertFired(account);
});
});
function createInstantiationService(): InstantiationService {
// Create a mock account picker view model
let providerId = 'azure';
let accountPickerViewModel = new AccountPickerViewModel(providerId, new AccountManagementTestService());
let mockAccountViewModel = TypeMoq.Mock.ofInstance(accountPickerViewModel);
let mockEvent = new Emitter<any>();
mockAccountViewModel.setup(x => x.updateAccountListEvent).returns(() => mockEvent.event);
// Create a mocked out instantiation service
let instantiationService = TypeMoq.Mock.ofType(InstantiationService, TypeMoq.MockBehavior.Strict);
instantiationService.setup(x => x.createInstance<AccountPickerViewModel>(TypeMoq.It.isValue(AccountPickerViewModel), TypeMoq.It.isAny()))
.returns(() => mockAccountViewModel.object);
// Create a mock account picker
let accountPicker = new AccountPicker(null, null, instantiationService.object, null);
let mockAccountDialog = TypeMoq.Mock.ofInstance(accountPicker);
mockAccountDialog.setup(x => x.addAccountCompleteEvent)
.returns(() => mockAddAccountCompleteEmitter.event);
mockAccountDialog.setup(x => x.addAccountErrorEvent)
.returns((msg) => mockAddAccountErrorEmitter.event);
mockAccountDialog.setup(x => x.addAccountStartEvent)
.returns(() => mockAddAccountStartEmitter.event);
mockAccountDialog.setup(x => x.onAccountSelectionChangeEvent)
.returns((account) => mockOnAccountSelectionChangeEvent.event);
mockAccountDialog.setup(x => x.render(TypeMoq.It.isAny()))
.returns((container) => undefined);
mockAccountDialog.setup(x => x.createAccountPickerComponent());
instantiationService.setup(x => x.createInstance<AccountPicker>(TypeMoq.It.isValue(AccountPicker), TypeMoq.It.isAny()))
.returns(() => mockAccountDialog.object);
return instantiationService.object;
}

View File

@@ -0,0 +1,148 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the Source EULA. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as data from 'data';
import * as assert from 'assert';
import * as TypeMoq from 'typemoq';
import { EventVerifierSingle } from 'sqltest/utils/eventVerifier';
import { Emitter } from 'vs/base/common/event';
import { AccountPickerViewModel } from 'sql/parts/accountManagement/accountPicker/accountPickerViewModel';
import { UpdateAccountListEventParams } from 'sql/services/accountManagement/eventTypes';
import { AccountManagementTestService } from 'sqltest/stubs/accountManagementStubs';
// SUITE STATE /////////////////////////////////////////////////////////////
let mockUpdateAccountEmitter: Emitter<UpdateAccountListEventParams>;
let providers: data.AccountProviderMetadata[];
let accounts: data.Account[];
suite('Account picker view model tests', () => {
setup(() => {
providers = [{
id: 'azure',
displayName: 'Azure'
}];
let account1 = {
key: { providerId: 'azure', accountId: 'account1' },
name: 'Account 1',
displayInfo: {
contextualDisplayName: 'Microsoft Account',
accountType: 'microsoft',
displayName: 'Account 1'
},
properties: [],
isStale: false
};
let account2 = {
key: { providerId: 'azure', accountId: 'account2' },
name: 'Account 2',
displayInfo: {
contextualDisplayName: 'Work/School Account',
accountType: 'microsoft',
displayName: 'Account 2'
},
properties: [],
isStale: true
};
accounts = [account1, account2];
// Setup event mocks
mockUpdateAccountEmitter = new Emitter<UpdateAccountListEventParams>();
});
test('Construction - Events are properly defined', () => {
// If: I create an account picker viewmodel
let mockAccountManagementService = getMockAccountManagementService(false, false);
let vm = new AccountPickerViewModel('azure', mockAccountManagementService.object);
// Then:
// ... The event for the view models should be properly initialized
assert.notEqual(vm.updateAccountListEvent, undefined);
// ... The event should properly fire
let argUpdateAccounts: UpdateAccountListEventParams = { providerId: providers[0].id, accountList: accounts };
let evUpdateAccounts = new EventVerifierSingle<UpdateAccountListEventParams>();
vm.updateAccountListEvent(evUpdateAccounts.eventHandler);
mockUpdateAccountEmitter.fire(argUpdateAccounts);
evUpdateAccounts.assertFired(argUpdateAccounts);
});
test('Initialize - Success', done => {
// Setup: Create a viewmodel with event handlers
let mockAccountManagementService = getMockAccountManagementService(true, true);
let evUpdateAccounts = new EventVerifierSingle<UpdateAccountListEventParams>();
let vm = getViewModel(mockAccountManagementService.object, evUpdateAccounts);
// If: I initialize the view model
vm.initialize()
.then(results => {
// Then:
// ... None of the events should have fired
evUpdateAccounts.assertNotFired();
// ... The account management service should have been called
mockAccountManagementService.verify(x => x.getAccountsForProvider(TypeMoq.It.isAny()), TypeMoq.Times.once());
// ... The results that were returned should be an array of account
assert.ok(Array.isArray(results));
assert.equal(results.length, 2);
assert.equal(results, accounts);
}).then(
() => done(),
err => done(err)
);
});
test('Initialize - Get accounts fails expects empty array', done => {
// Setup: Create a mock account management service that rejects the promise
let mockAccountManagementService = getMockAccountManagementService(true, false);
let evUpdateAccounts = new EventVerifierSingle<UpdateAccountListEventParams>();
let vm = getViewModel(mockAccountManagementService.object, evUpdateAccounts);
// If: I initialize the view model
vm.initialize()
.then(result => {
// Then:
// ... None of the events should have fired
evUpdateAccounts.assertNotFired();
// ... The account management service should have been called
mockAccountManagementService.verify(x => x.getAccountsForProvider(TypeMoq.It.isAny()), TypeMoq.Times.once());
// ... The results should be an empty array
assert.ok(Array.isArray(result));
assert.equal(result.length, 0);
assert.equal(result, []);
}).then(
() => done(),
err => done()
);
});
});
function getMockAccountManagementService(resolveProviders: boolean, resolveAccounts: boolean): TypeMoq.Mock<AccountManagementTestService> {
let mockAccountManagementService = TypeMoq.Mock.ofType(AccountManagementTestService);
mockAccountManagementService.setup(x => x.getAccountProviderMetadata())
.returns(() => resolveProviders ? Promise.resolve(providers) : Promise.reject(null).then());
mockAccountManagementService.setup(x => x.getAccountsForProvider(TypeMoq.It.isAny()))
.returns(() => resolveAccounts ? Promise.resolve(accounts) : Promise.reject(null).then());
mockAccountManagementService.setup(x => x.updateAccountListEvent)
.returns(() => mockUpdateAccountEmitter.event);
return mockAccountManagementService;
}
function getViewModel(
ams: AccountManagementTestService,
evUpdate: EventVerifierSingle<UpdateAccountListEventParams>
): AccountPickerViewModel {
let vm = new AccountPickerViewModel('azure', ams);
vm.updateAccountListEvent(evUpdate.eventHandler);
return vm;
}

View File

@@ -35,7 +35,7 @@ suite('Account Management Dialog ViewModel Tests', () => {
name: 'Account 1',
displayInfo: {
contextualDisplayName: 'Microsoft Account',
contextualLogo: null,
accountType: 'microsoft',
displayName: 'Account 1'
},
properties: [],
@@ -46,7 +46,7 @@ suite('Account Management Dialog ViewModel Tests', () => {
name: 'Account 2',
displayInfo: {
contextualDisplayName: 'Work/School Account',
contextualLogo: null,
accountType: 'work_school',
displayName: 'Account 2'
},
properties: [],
@@ -116,8 +116,8 @@ suite('Account Management Dialog ViewModel Tests', () => {
assert.equal(results[0].addedProvider, providers[0]);
assert.equal(results[0].initialAccounts, accounts);
}).then(
() => done(),
err => done(err)
() => done(),
err => done(err)
);
});
@@ -145,8 +145,8 @@ suite('Account Management Dialog ViewModel Tests', () => {
assert.equal(results.length, 0);
})
.then(
() => done(),
err => done(err)
() => done(),
err => done(err)
);
});
@@ -175,8 +175,8 @@ suite('Account Management Dialog ViewModel Tests', () => {
assert.equal(result[0].addedProvider, providers[0]);
assert.equal(result[0].initialAccounts, accounts);
}).then(
() => done(),
err => done()
() => done(),
err => done()
);
});
});

View File

@@ -0,0 +1,139 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the Source EULA. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as TypeMoq from 'typemoq';
import { Emitter } from 'vs/base/common/event';
import { InstantiationService } from 'vs/platform/instantiation/common/instantiationService';
import { AutoOAuthDialog } from 'sql/parts/accountManagement/autoOAuthDialog/autoOAuthDialog';
import { AutoOAuthDialogController } from 'sql/parts/accountManagement/autoOAuthDialog/autoOAuthDialogController';
import { AccountManagementTestService } from 'sqltest/stubs/accountManagementStubs';
import { ErrorMessageServiceStub } from 'sqltest/stubs/errorMessageServiceStub';
import { ContextKeyServiceStub } from 'sqltest/stubs/contextKeyServiceStub';
// TESTS ///////////////////////////////////////////////////////////////////
suite('auto OAuth dialog controller tests', () => {
let instantiationService: TypeMoq.Mock<InstantiationService>;
let mockAutoOAuthDialog: TypeMoq.Mock<AutoOAuthDialog>;
let mockAccountManagementService: TypeMoq.Mock<AccountManagementTestService>;
let mockErrorMessageService: TypeMoq.Mock<ErrorMessageServiceStub>;
let autoOAuthDialogController: AutoOAuthDialogController;
let mockOnCancelEvent: Emitter<void>;
let mockOnAddAccountEvent: Emitter<void>;
let mockOnCloseEvent: Emitter<void>;
let providerId = 'azure';
let title = 'Add Account';
let message = 'This is the dialog description';
let userCode = 'abcde';
let uri = 'uri';
setup(() => {
mockOnCancelEvent = new Emitter<void>();
mockOnAddAccountEvent = new Emitter<void>();
mockOnCloseEvent = new Emitter<void>();
// Create a mock auto OAuth dialog
let autoOAuthDialog = new AutoOAuthDialog(null, null, null, null, new ContextKeyServiceStub());
mockAutoOAuthDialog = TypeMoq.Mock.ofInstance(autoOAuthDialog);
mockAutoOAuthDialog.setup(x => x.onCancel).returns(() => mockOnCancelEvent.event);
mockAutoOAuthDialog.setup(x => x.onHandleAddAccount).returns(() => mockOnAddAccountEvent.event);
mockAutoOAuthDialog.setup(x => x.onCloseEvent).returns(() => mockOnCloseEvent.event);
mockAutoOAuthDialog.setup(x => x.render());
mockAutoOAuthDialog.setup(x => x.open(TypeMoq.It.isAny(), TypeMoq.It.isAny(), TypeMoq.It.isAny(), TypeMoq.It.isAny()));
mockAutoOAuthDialog.setup(x => x.close()).callback(() => {
mockOnCloseEvent.fire();
});
// Create a mocked out instantiation service
instantiationService = TypeMoq.Mock.ofType(InstantiationService, TypeMoq.MockBehavior.Strict);
instantiationService.setup(x => x.createInstance<AutoOAuthDialog>(TypeMoq.It.isValue(AutoOAuthDialog)))
.returns(() => mockAutoOAuthDialog.object);
// Create a mocked account management service
let accountManagementTestService = new AccountManagementTestService();
mockAccountManagementService = TypeMoq.Mock.ofInstance(accountManagementTestService);
mockAccountManagementService.setup(x => x.copyUserCodeAndOpenBrowser(TypeMoq.It.isAny(), TypeMoq.It.isAny()));
// Create a mocked error message service
let errorMessageServiceStub = new ErrorMessageServiceStub();
mockErrorMessageService = TypeMoq.Mock.ofInstance(errorMessageServiceStub);
mockErrorMessageService.setup(x => x.showDialog(TypeMoq.It.isAny(), TypeMoq.It.isAny(), TypeMoq.It.isAny()));
// Create a mocked auto OAuth dialog controller
autoOAuthDialogController = new AutoOAuthDialogController(instantiationService.object, mockAccountManagementService.object, mockErrorMessageService.object);
});
test('Open auto OAuth when the flyout is already open, return an error', () => {
// If: Open auto OAuth dialog first time
autoOAuthDialogController.openAutoOAuthDialog(providerId, title, message, userCode, uri);
// Then: It should open the flyout successfully
mockAutoOAuthDialog.verify(x => x.open(title, message, userCode, uri), TypeMoq.Times.once());
mockErrorMessageService.verify(x => x.showDialog(TypeMoq.It.isAny(), TypeMoq.It.isAny(), TypeMoq.It.isAny()), TypeMoq.Times.never());
// If: a oauth flyout is already open
autoOAuthDialogController.openAutoOAuthDialog(providerId, title, message, userCode, uri);
// Then: An error dialog should have been opened
mockErrorMessageService.verify(x => x.showDialog(TypeMoq.It.isAny(), TypeMoq.It.isAny(), TypeMoq.It.isAny()), TypeMoq.Times.once());
});
test('Close auto OAuth dialog successfully', () => {
let title = 'Add Account';
let message = 'This is the dialog description';
let userCode = 'abcde';
let uri = 'uri';
autoOAuthDialogController.openAutoOAuthDialog(providerId, title, message, userCode, uri);
// If: closeAutoOAuthDialog is called
autoOAuthDialogController.closeAutoOAuthDialog();
// Then: it should close the dialog
mockAutoOAuthDialog.verify(x => x.close(), TypeMoq.Times.once());
});
test('Open and close auto OAuth dialog multiple times should work properly', () => {
let title = 'Add Account';
let message = 'This is the dialog description';
let userCode = 'abcde';
let uri = 'uri';
autoOAuthDialogController.openAutoOAuthDialog(providerId, title, message, userCode, uri);
autoOAuthDialogController.closeAutoOAuthDialog();
// If: Open the flyout second time
autoOAuthDialogController.openAutoOAuthDialog(providerId, title, message, userCode, uri);
// Then: It should open the flyout twice successfully
mockAutoOAuthDialog.verify(x => x.open(TypeMoq.It.isAny(), TypeMoq.It.isAny(), TypeMoq.It.isAny(), TypeMoq.It.isAny()), TypeMoq.Times.exactly(2));
mockErrorMessageService.verify(x => x.showDialog(TypeMoq.It.isAny(), TypeMoq.It.isAny(), TypeMoq.It.isAny()), TypeMoq.Times.never());
});
test('Copy and open button in auto OAuth dialog should work properly', () => {
let title = 'Add Account';
let message = 'This is the dialog description';
let userCode = 'abcde';
let uri = 'uri';
autoOAuthDialogController.openAutoOAuthDialog(providerId, title, message, userCode, uri);
// If: the 'copy & open' button in auto Oauth dialog is selected
mockOnAddAccountEvent.fire();
// Then: copyUserCodeAndOpenBrowser should get called
mockAccountManagementService.verify(x => x.copyUserCodeAndOpenBrowser(userCode, uri), TypeMoq.Times.once());
});
// TODO: Test for cancel button
});

View File

@@ -0,0 +1,254 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the Source EULA. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as data from 'data';
import * as TypeMoq from 'typemoq';
import { Emitter } from 'vs/base/common/event';
import { IConnectionProfile } from 'sql/parts/connection/common/interfaces';
import { FirewallRuleDialog } from 'sql/parts/accountManagement/firewallRuleDialog/firewallRuleDialog';
import { FirewallRuleViewModel } from 'sql/parts/accountManagement/firewallRuleDialog/firewallRuleViewModel';
import { FirewallRuleDialogController } from 'sql/parts/accountManagement/firewallRuleDialog/firewallRuleDialogController';
import { AccountManagementTestService } from 'sqltest/stubs/accountManagementStubs';
import { ResourceProviderStub } from 'sqltest/stubs/resourceProviderServiceStub';
import { ErrorMessageServiceStub } from 'sqltest/stubs/errorMessageServiceStub';
import { InstantiationService } from 'vs/platform/instantiation/common/instantiationService';
import { ContextKeyServiceStub } from 'sqltest/stubs/contextKeyServiceStub';
import { Deferred } from 'sql/base/common/promise';
// TESTS ///////////////////////////////////////////////////////////////////
suite('Firewall rule dialog controller tests', () => {
let connectionProfile: IConnectionProfile;
let account: data.Account;
let IPAddress = '250.222.155.198';
let mockOnAddAccountErrorEvent: Emitter<string>;
let mockOnCreateFirewallRule: Emitter<void>;
let instantiationService: TypeMoq.Mock<InstantiationService>;
let mockFirewallRuleViewModel: TypeMoq.Mock<FirewallRuleViewModel>;
let mockFirewallRuleDialog: TypeMoq.Mock<FirewallRuleDialog>;
setup(() => {
account = {
key: { providerId: 'azure', accountId: 'account1' },
displayInfo: {
contextualDisplayName: 'Microsoft Account',
accountType: 'microsoft',
displayName: 'Account 1'
},
properties: [],
isStale: false
};
mockOnAddAccountErrorEvent = new Emitter<string>();
mockOnCreateFirewallRule = new Emitter<void>();
// Create a mock firewall rule view model
let firewallRuleViewModel = new FirewallRuleViewModel();
mockFirewallRuleViewModel = TypeMoq.Mock.ofInstance(firewallRuleViewModel);
mockFirewallRuleViewModel.setup(x => x.updateDefaultValues(TypeMoq.It.isAny()))
.returns((ipAddress) => undefined);
mockFirewallRuleViewModel.object.selectedAccount = account;
mockFirewallRuleViewModel.object.isIPAddressSelected = true;
// Create a mocked out instantiation service
instantiationService = TypeMoq.Mock.ofType(InstantiationService, TypeMoq.MockBehavior.Strict);
instantiationService.setup(x => x.createInstance<FirewallRuleViewModel>(TypeMoq.It.isValue(FirewallRuleViewModel)))
.returns(() => mockFirewallRuleViewModel.object);
// Create a mock account picker
let firewallRuleDialog = new FirewallRuleDialog(null, null, null, instantiationService.object, null, null, new ContextKeyServiceStub());
mockFirewallRuleDialog = TypeMoq.Mock.ofInstance(firewallRuleDialog);
let mockEvent = new Emitter<any>();
mockFirewallRuleDialog.setup(x => x.onCancel)
.returns(() => mockEvent.event);
mockFirewallRuleDialog.setup(x => x.onCreateFirewallRule)
.returns(() => mockOnCreateFirewallRule.event);
mockFirewallRuleDialog.setup(x => x.onAddAccountErrorEvent)
.returns((msg) => mockOnAddAccountErrorEvent.event);
mockFirewallRuleDialog.setup(x => x.render());
mockFirewallRuleDialog.setup(x => x.open());
mockFirewallRuleDialog.setup(x => x.close());
instantiationService.setup(x => x.createInstance<FirewallRuleDialog>(TypeMoq.It.isValue(FirewallRuleDialog)))
.returns(() => mockFirewallRuleDialog.object);
connectionProfile = {
serverName: 'new server',
databaseName: 'database',
userName: 'user',
password: 'password',
authenticationType: '',
savePassword: true,
groupFullName: 'g2/g2-2',
groupId: 'group id',
getOptionsKey: undefined,
matches: undefined,
providerName: 'MSSQL',
options: {},
saveProfile: true,
id: undefined
};
});
test('Add Account Failure - Error Message Shown', () => {
// ... Create a mock instance of the error message service
let errorMessageServiceStub = new ErrorMessageServiceStub();
let mockErrorMessageService = TypeMoq.Mock.ofInstance(errorMessageServiceStub);
mockErrorMessageService.setup(x => x.showDialog(TypeMoq.It.isAny(), TypeMoq.It.isAny(), TypeMoq.It.isAny()));
// ... Create instance of the controller with an opened dialog
let controller = new FirewallRuleDialogController(instantiationService.object, null, null, mockErrorMessageService.object);
controller.openFirewallRuleDialog(connectionProfile, IPAddress, 'resourceID');
// If: The firewall rule dialog reports a failure
mockOnAddAccountErrorEvent.fire('Error message');
// Then: An error dialog should have been opened
mockErrorMessageService.verify(x => x.showDialog(TypeMoq.It.isAny(), TypeMoq.It.isAny(), TypeMoq.It.isAny()), TypeMoq.Times.once());
});
test('create firewall rule success', (done) => {
let deferredPromise = new Deferred();
mockFirewallRuleDialog.setup(x => x.onServiceComplete())
.callback(() => {
deferredPromise.resolve(true);
});
// ... Create a mock instance of the account management test service
let mockAccountManagementService = getMockAccountManagementService(true);
// ... Create a mock instance of the resource provider
let mockResourceProvider = getMockResourceProvider(true, { result: true, errorMessage: '' });
// ... Create instance of the controller with an opened dialog
let controller = new FirewallRuleDialogController(instantiationService.object, mockResourceProvider.object, mockAccountManagementService.object, null);
controller.openFirewallRuleDialog(connectionProfile, IPAddress, 'resourceID');
// If: The firewall rule dialog's create firewall rule get fired
mockOnCreateFirewallRule.fire();
// Then: it should get security token from account management service and call create firewall rule in resource provider
deferredPromise.promise.then(() => {
mockAccountManagementService.verify(x => x.getSecurityToken(TypeMoq.It.isAny()), TypeMoq.Times.once());
mockResourceProvider.verify(x => x.createFirewallRule(TypeMoq.It.isAny(), TypeMoq.It.isAny(), TypeMoq.It.isAny()), TypeMoq.Times.once());
mockFirewallRuleDialog.verify(x => x.close(), TypeMoq.Times.once());
mockFirewallRuleDialog.verify(x => x.onServiceComplete(), TypeMoq.Times.once());
done();
});
});
test('create firewall rule fails during getSecurity', (done) => {
let deferredPromise = new Deferred();
// ... Create a mock instance of the error message service
let mockErrorMessageService = getMockErrorMessageService(deferredPromise);
// ... Create a mock instance of the account management test service
let mockAccountManagementService = getMockAccountManagementService(false);
// ... Create a mock instance of the resource provider
let mockResourceProvider = getMockResourceProvider(true, { result: true, errorMessage: '' });
// ... Create instance of the controller with an opened dialog
let controller = new FirewallRuleDialogController(instantiationService.object, mockResourceProvider.object, mockAccountManagementService.object, mockErrorMessageService.object);
controller.openFirewallRuleDialog(connectionProfile, IPAddress, 'resourceID');
// If: The firewall rule dialog's create firewall rule get fired
mockOnCreateFirewallRule.fire();
// Then: it should get security token from account management service and an error dialog should have been opened
deferredPromise.promise.then(() => {
mockAccountManagementService.verify(x => x.getSecurityToken(TypeMoq.It.isAny()), TypeMoq.Times.once());
mockErrorMessageService.verify(x => x.showDialog(TypeMoq.It.isAny(), TypeMoq.It.isAny(), TypeMoq.It.isAny()), TypeMoq.Times.once());
mockResourceProvider.verify(x => x.createFirewallRule(TypeMoq.It.isAny(), TypeMoq.It.isAny(), TypeMoq.It.isAny()), TypeMoq.Times.never());
done();
});
});
test('create firewall rule fails during createFirewallRule in ResourceProvider - result is false', (done) => {
let deferredPromise = new Deferred();
// ... Create a mock instance of the error message service
let mockErrorMessageService = getMockErrorMessageService(deferredPromise);
// ... Create a mock instance of the account management test service
let mockAccountManagementService = getMockAccountManagementService(true);
// ... Create a mock instance of the resource provider
let mockResourceProvider = getMockResourceProvider(true, { result: false, errorMessage: '' });
// ... Create instance of the controller with an opened dialog
let controller = new FirewallRuleDialogController(instantiationService.object, mockResourceProvider.object, mockAccountManagementService.object, mockErrorMessageService.object);
controller.openFirewallRuleDialog(connectionProfile, IPAddress, 'resourceID');
// If: The firewall rule dialog's create firewall rule get fired
mockOnCreateFirewallRule.fire();
// Then: it should get security token from account management service and an error dialog should have been opened
deferredPromise.promise.then(() => {
mockAccountManagementService.verify(x => x.getSecurityToken(TypeMoq.It.isAny()), TypeMoq.Times.once());
mockResourceProvider.verify(x => x.createFirewallRule(TypeMoq.It.isAny(), TypeMoq.It.isAny(), TypeMoq.It.isAny()), TypeMoq.Times.once());
mockErrorMessageService.verify(x => x.showDialog(TypeMoq.It.isAny(), TypeMoq.It.isAny(), TypeMoq.It.isAny()), TypeMoq.Times.once());
done();
});
});
test('create firewall rule fails during createFirewallRule in ResourceProvider - reject promise', (done) => {
let deferredPromise = new Deferred();
// ... Create a mock instance of the error message service
let mockErrorMessageService = getMockErrorMessageService(deferredPromise);
// ... Create a mock instance of the account management test service
let mockAccountManagementService = getMockAccountManagementService(true);
// ... Create a mock instance of the resource provider
let mockResourceProvider = getMockResourceProvider(false);
// ... Create instance of the controller with an opened dialog
let controller = new FirewallRuleDialogController(instantiationService.object, mockResourceProvider.object, mockAccountManagementService.object, mockErrorMessageService.object);
controller.openFirewallRuleDialog(connectionProfile, IPAddress, 'resourceID');
// If: The firewall rule dialog's create firewall rule get fired
mockOnCreateFirewallRule.fire();
// Then: it should get security token from account management service and an error dialog should have been opened
deferredPromise.promise.then(() => {
mockAccountManagementService.verify(x => x.getSecurityToken(TypeMoq.It.isAny()), TypeMoq.Times.once());
mockResourceProvider.verify(x => x.createFirewallRule(TypeMoq.It.isAny(), TypeMoq.It.isAny(), TypeMoq.It.isAny()), TypeMoq.Times.once());
mockErrorMessageService.verify(x => x.showDialog(TypeMoq.It.isAny(), TypeMoq.It.isAny(), TypeMoq.It.isAny()), TypeMoq.Times.once());
done();
});
});
});
function getMockAccountManagementService(resolveSecurityToken: boolean): TypeMoq.Mock<AccountManagementTestService> {
let accountManagementTestService = new AccountManagementTestService();
let mockAccountManagementService = TypeMoq.Mock.ofInstance(accountManagementTestService);
mockAccountManagementService.setup(x => x.getSecurityToken(TypeMoq.It.isAny()))
.returns(() => resolveSecurityToken ? Promise.resolve({}) : Promise.reject(null).then());
return mockAccountManagementService;
}
function getMockResourceProvider(resolveCreateFirewallRule: boolean, response?: data.CreateFirewallRuleResponse): TypeMoq.Mock<ResourceProviderStub> {
let resourceProviderStub = new ResourceProviderStub();
let mockResourceProvider = TypeMoq.Mock.ofInstance(resourceProviderStub);
mockResourceProvider.setup(x => x.createFirewallRule(TypeMoq.It.isAny(), TypeMoq.It.isAny(), TypeMoq.It.isAny()))
.returns(() => resolveCreateFirewallRule ? Promise.resolve(response) : Promise.reject(null).then());
return mockResourceProvider;
}
function getMockErrorMessageService(deferredPromise: Deferred<{}>): TypeMoq.Mock<ErrorMessageServiceStub> {
let errorMessageServiceStub = new ErrorMessageServiceStub();
let mockErrorMessageService = TypeMoq.Mock.ofInstance(errorMessageServiceStub);
mockErrorMessageService.setup(x => x.showDialog(TypeMoq.It.isAny(), TypeMoq.It.isAny(), TypeMoq.It.isAny())).callback(() => {
deferredPromise.resolve(true);
});
return mockErrorMessageService;
}

View File

@@ -0,0 +1,44 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the Source EULA. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as assert from 'assert';
import { FirewallRuleViewModel } from 'sql/parts/accountManagement/firewallRuleDialog/firewallRuleViewModel';
suite('Firewall rule view model tests', () => {
let viewModel: FirewallRuleViewModel;
setup(() => {
viewModel = new FirewallRuleViewModel();
});
test('update default values to 250.222.155.198 should calculate the correct default subnet IP range', () => {
let IPAddress = '250.222.155.198';
viewModel.updateDefaultValues(IPAddress);
assert.equal(IPAddress, viewModel.defaultIPAddress);
assert.equal('250.222.155.0', viewModel.defaultFromSubnetIPRange);
assert.equal('250.222.155.255', viewModel.defaultToSubnetIPRange);;
});
test('update default values to 250.222.155.0 should calculate the correct default subnet IP range', () => {
let IPAddress = '250.222.155.2';
viewModel.updateDefaultValues(IPAddress);
assert.equal(IPAddress, viewModel.defaultIPAddress);
assert.equal('250.222.155.0', viewModel.defaultFromSubnetIPRange);
assert.equal('250.222.155.255', viewModel.defaultToSubnetIPRange);
});
test('subnet IP range should return the correct values', () => {
let IPAddress = '250.222.155.198';
viewModel.updateDefaultValues(IPAddress);
assert.equal('250.222.155.0', viewModel.fromSubnetIPRange);
assert.equal('250.222.155.255', viewModel.toSubnetIPRange);
viewModel.fromSubnetIPRange = '250.222.155.100';
viewModel.toSubnetIPRange = '250.222.155.220';
assert.equal('250.222.155.100', viewModel.fromSubnetIPRange);
assert.equal('250.222.155.220', viewModel.toSubnetIPRange);
});
});

View File

@@ -10,10 +10,9 @@ import * as TypeMoq from 'typemoq';
import { ConnectionConfig, ISaveGroupResult } from 'sql/parts/connection/common/connectionConfig';
import { IConnectionProfile, IConnectionProfileStore } from 'sql/parts/connection/common/interfaces';
import { ConnectionProfile } from 'sql/parts/connection/common/connectionProfile';
import { ConfigurationTarget, IConfigurationValue } from 'vs/workbench/services/configuration/common/configurationEditing';
import { IConfigurationValue as TConfigurationValue } from 'vs/platform/configuration/common/configuration';
import { ConfigurationTarget } from 'vs/platform/configuration/common/configuration';
import { WorkspaceConfigurationTestService } from 'sqltest/stubs/workspaceConfigurationTestService';
import { ConfigurationEditingService } from 'vs/workbench/services/configuration/node/configurationEditingService';
import { IConfigurationValue as TConfigurationValue, ConfigurationEditingService } from 'vs/workbench/services/configuration/node/configurationEditingService';
import * as Constants from 'sql/parts/connection/common/constants';
import { IConnectionProfileGroup, ConnectionProfileGroup } from 'sql/parts/connection/common/connectionProfileGroup';
import { TPromise } from 'vs/base/common/winjs.base';
@@ -23,6 +22,7 @@ import data = require('data');
import { Emitter } from 'vs/base/common/event';
suite('SQL ConnectionConfig tests', () => {
/*
let capabilitiesService: TypeMoq.Mock<CapabilitiesService>;
let workspaceConfigurationServiceMock: TypeMoq.Mock<WorkspaceConfigurationTestService>;
let configEditingServiceMock: TypeMoq.Mock<ConfigurationEditingService>;
@@ -927,5 +927,11 @@ suite('SQL ConnectionConfig tests', () => {
}
done();
});
*/
test('fixConnectionIds should replace duplicate ids with new ones', (done) => {
done();
});
});

View File

@@ -22,7 +22,8 @@ suite('ConnectionDialogService tests', () => {
setup(() => {
let errorMessageService = getMockErrorMessageService();
connectionDialogService = new ConnectionDialogService(undefined, undefined, undefined, errorMessageService.object, undefined);
connectionDialogService = new ConnectionDialogService(undefined, undefined, undefined, errorMessageService.object,
undefined, undefined, undefined, undefined);
mockConnectionManagementService = TypeMoq.Mock.ofType(ConnectionManagementService, TypeMoq.MockBehavior.Strict, {}, {});
(connectionDialogService as any)._connectionManagementService = mockConnectionManagementService.object;
mockConnectionDialog = TypeMoq.Mock.ofType(ConnectionDialogWidget, TypeMoq.MockBehavior.Strict,

View File

@@ -16,12 +16,14 @@ import {
} from 'sql/parts/connection/common/connectionManagement';
import * as Constants from 'sql/parts/connection/common/constants';
import * as Utils from 'sql/parts/connection/common/utils';
import { IHandleFirewallRuleResult } from 'sql/parts/accountManagement/common/interfaces';
import { WorkbenchEditorTestService } from 'sqltest/stubs/workbenchEditorTestService';
import { IConnectionProfile } from 'sql/parts/connection/common/interfaces';
import { EditorGroupTestService } from 'sqltest/stubs/editorGroupService';
import { CapabilitiesTestService } from 'sqltest/stubs/capabilitiesTestService';
import { ConnectionProviderStub } from 'sqltest/stubs/connectionProviderStub';
import { ResourceProviderStub } from 'sqltest/stubs/resourceProviderServiceStub';
import * as data from 'data';
@@ -40,8 +42,8 @@ suite('SQL ConnectionManagementService tests', () => {
let editorGroupService: TypeMoq.Mock<EditorGroupTestService>;
let connectionStatusManager: ConnectionStatusManager;
let mssqlConnectionProvider: TypeMoq.Mock<ConnectionProviderStub>;
let otherConnectionProvider: TypeMoq.Mock<ConnectionProviderStub>;
let workspaceConfigurationServiceMock: TypeMoq.Mock<WorkspaceConfigurationTestService>;
let resourceProviderStubMock: TypeMoq.Mock<ResourceProviderStub>;
let none: void;
@@ -68,6 +70,9 @@ suite('SQL ConnectionManagementService tests', () => {
let connectionManagementService: ConnectionManagementService;
let configResult: { [key: string]: any } = {};
let handleFirewallRuleResult: IHandleFirewallRuleResult;
let resolveHandleFirewallRuleDialog: boolean;
let isFirewallRuleAdded: boolean;
setup(() => {
@@ -78,7 +83,8 @@ suite('SQL ConnectionManagementService tests', () => {
editorGroupService = TypeMoq.Mock.ofType(EditorGroupTestService);
connectionStatusManager = new ConnectionStatusManager(capabilitiesService);
mssqlConnectionProvider = TypeMoq.Mock.ofType(ConnectionProviderStub);
otherConnectionProvider = TypeMoq.Mock.ofType(ConnectionProviderStub);
let resourceProviderStub = new ResourceProviderStub();
resourceProviderStubMock = TypeMoq.Mock.ofInstance(resourceProviderStub);
connectionDialogService.setup(x => x.showDialog(TypeMoq.It.isAny(), TypeMoq.It.isAny(), TypeMoq.It.isAny(), undefined)).returns(() => TPromise.as(none));
connectionDialogService.setup(x => x.showDialog(TypeMoq.It.isAny(), TypeMoq.It.isAny(), undefined, undefined)).returns(() => TPromise.as(none));
@@ -100,10 +106,28 @@ suite('SQL ConnectionManagementService tests', () => {
connectionStore.setup(x => x.isPasswordRequired(TypeMoq.It.isAny())).returns(() => true);
mssqlConnectionProvider.setup(x => x.connect(TypeMoq.It.isAny(), TypeMoq.It.isAny())).returns(() => undefined);
otherConnectionProvider.setup(x => x.connect(TypeMoq.It.isAny(), TypeMoq.It.isAny())).returns(() => undefined);
// setup configuration to return a config that can be modified later.
// Setup resource provider
handleFirewallRuleResult = {
canHandleFirewallRule: false,
ipAddress: '123.123.123.123',
resourceProviderId: 'Azure'
};
resourceProviderStubMock.setup(x => x.handleFirewallRule(TypeMoq.It.isAny(), TypeMoq.It.isAny(), TypeMoq.It.isAny()))
.returns(() => Promise.resolve(handleFirewallRuleResult));
resolveHandleFirewallRuleDialog = true;
isFirewallRuleAdded = true;
resourceProviderStubMock.setup(x => x.showFirewallRuleDialog(TypeMoq.It.isAny(), TypeMoq.It.isAny(), TypeMoq.It.isAny()))
.returns(() => {
if (resolveHandleFirewallRuleDialog) {
return isFirewallRuleAdded ? Promise.resolve(true) : Promise.resolve(false);
} else {
return Promise.reject(null).then();
}
});
// Setup configuration to return a config that can be modified later.
workspaceConfigurationServiceMock = TypeMoq.Mock.ofType(WorkspaceConfigurationTestService);
workspaceConfigurationServiceMock.setup(x => x.getConfiguration(Constants.sqlConfigSectionName))
.returns(() => configResult);
@@ -125,36 +149,44 @@ suite('SQL ConnectionManagementService tests', () => {
undefined,
undefined,
undefined,
undefined,
workspaceConfigurationServiceMock.object,
undefined,
capabilitiesService,
undefined,
editorGroupService.object,
undefined,
undefined,
resourceProviderStubMock.object,
undefined,
undefined
);
return connectionManagementService;
}
function verifyShowDialog(connectionProfile: IConnectionProfile, connectionType: ConnectionType, uri: string, error?: string, didShow: boolean = true): void {
function verifyShowConnectionDialog(connectionProfile: IConnectionProfile, connectionType: ConnectionType, uri: string, connectionResult?: IConnectionResult, didShow: boolean = true): void {
if (connectionProfile) {
connectionDialogService.verify(x => x.showDialog(
TypeMoq.It.isAny(),
TypeMoq.It.is<INewConnectionParams>(p => p.connectionType === connectionType && (uri === undefined || p.input.uri === uri)),
TypeMoq.It.is<IConnectionProfile>(c => c.serverName === connectionProfile.serverName), error),
TypeMoq.It.is<IConnectionProfile>(c => c.serverName === connectionProfile.serverName),
connectionResult ? TypeMoq.It.is<IConnectionResult>(r => r.errorMessage === connectionResult.errorMessage && r.callStack === connectionResult.callStack) : undefined),
didShow ? TypeMoq.Times.once() : TypeMoq.Times.never());
} else {
connectionDialogService.verify(x => x.showDialog(
TypeMoq.It.isAny(),
TypeMoq.It.is<INewConnectionParams>(p => p.connectionType === connectionType && ((uri === undefined && p.input === undefined) || p.input.uri === uri)),
undefined, error), didShow ? TypeMoq.Times.once() : TypeMoq.Times.never());
undefined,
connectionResult ? TypeMoq.It.is<IConnectionResult>(r => r.errorMessage === connectionResult.errorMessage && r.callStack === connectionResult.callStack) : undefined),
didShow ? TypeMoq.Times.once() : TypeMoq.Times.never());
}
}
function verifyShowFirewallRuleDialog(connectionProfile: IConnectionProfile, didShow: boolean = true): void {
resourceProviderStubMock.verify(x => x.showFirewallRuleDialog(
TypeMoq.It.is<IConnectionProfile>(c => c.serverName === connectionProfile.serverName),
TypeMoq.It.isAny(),
TypeMoq.It.isAny()),
didShow ? TypeMoq.Times.once() : TypeMoq.Times.never());
}
function verifyOptions(options?: IConnectionCompletionOptions, fromDialog?: boolean): void {
@@ -174,7 +206,7 @@ suite('SQL ConnectionManagementService tests', () => {
}
function connect(uri: string, options?: IConnectionCompletionOptions, fromDialog?: boolean, connection?: IConnectionProfile, error?: string): Promise<IConnectionResult> {
function connect(uri: string, options?: IConnectionCompletionOptions, fromDialog?: boolean, connection?: IConnectionProfile, error?: string, errorCode?: number, errorCallStack?: string): Promise<IConnectionResult> {
let connectionToUse = connection ? connection : connectionProfile;
return new Promise<IConnectionResult>((resolve, reject) => {
let id = connectionToUse.getOptionsKey();
@@ -188,8 +220,8 @@ suite('SQL ConnectionManagementService tests', () => {
userName: connectionToUse.userName
},
errorMessage: error,
errorNumber: undefined,
messages: error,
errorNumber: errorCode,
messages: errorCallStack,
ownerUri: uri ? uri : defaultUri,
serverInfo: undefined
};
@@ -207,7 +239,7 @@ suite('SQL ConnectionManagementService tests', () => {
test('showConnectionDialog should open the dialog with default type given no parameters', done => {
connectionManagementService.showConnectionDialog().then(() => {
verifyShowDialog(undefined, ConnectionType.default, undefined);
verifyShowConnectionDialog(undefined, ConnectionType.default, undefined);
done();
}).catch(err => {
done(err);
@@ -227,7 +259,7 @@ suite('SQL ConnectionManagementService tests', () => {
runQueryOnCompletion: RunQueryOnConnectionMode.executeQuery
};
connectionManagementService.showConnectionDialog(params).then(() => {
verifyShowDialog(undefined, params.connectionType, params.input.uri);
verifyShowConnectionDialog(undefined, params.connectionType, params.input.uri);
done();
}).catch(err => {
done(err);
@@ -253,7 +285,7 @@ suite('SQL ConnectionManagementService tests', () => {
assert.notEqual(saveConnection, undefined, `profile was not added to the connections`);
assert.equal(saveConnection.serverName, connectionProfile.serverName, `Server names are different`);
connectionManagementService.showConnectionDialog(params).then(() => {
verifyShowDialog(connectionProfile, params.connectionType, params.input.uri);
verifyShowConnectionDialog(connectionProfile, params.connectionType, params.input.uri);
done();
}).catch(err => {
done(err);
@@ -268,7 +300,7 @@ suite('SQL ConnectionManagementService tests', () => {
saveTheConnection: true,
showDashboard: false,
showConnectionDialogOnError: false,
showFirewallRuleOnError: false
showFirewallRuleOnError: true
};
connect(uri, options).then(() => {
@@ -319,7 +351,7 @@ suite('SQL ConnectionManagementService tests', () => {
saveTheConnection: true,
showDashboard: false,
showConnectionDialogOnError: true,
showFirewallRuleOnError: false
showFirewallRuleOnError: true
};
connect(uri, options).then(() => {
@@ -359,20 +391,29 @@ suite('SQL ConnectionManagementService tests', () => {
test('failed connection should open the dialog if connection fails', done => {
let uri = undefined;
let error: string = 'error';
let errorCode: number = 111;
let errorCallStack: string = 'error call stack';
let expectedConnection: boolean = false;
let expectedError: string = error;
let options: IConnectionCompletionOptions = {
params: undefined,
saveTheConnection: false,
showDashboard: false,
showConnectionDialogOnError: true,
showFirewallRuleOnError: false
showFirewallRuleOnError: true
};
connect(uri, options, false, connectionProfile, error).then(result => {
let connectionResult: IConnectionResult = {
connected: expectedConnection,
errorMessage: error,
errorCode: errorCode,
callStack: errorCallStack
};
connect(uri, options, false, connectionProfile, error, errorCode, errorCallStack).then(result => {
assert.equal(result.connected, expectedConnection);
assert.equal(result.errorMessage, expectedError);
verifyShowDialog(connectionProfile, ConnectionType.default, uri, error);
assert.equal(result.errorMessage, connectionResult.errorMessage);
verifyShowFirewallRuleDialog(connectionProfile, false);
verifyShowConnectionDialog(connectionProfile, ConnectionType.default, uri, connectionResult);
done();
}).catch(err => {
done(err);
@@ -382,8 +423,73 @@ suite('SQL ConnectionManagementService tests', () => {
test('failed connection should not open the dialog if the option is set to false even if connection fails', done => {
let uri = undefined;
let error: string = 'error when options set to false';
let errorCode: number = 111;
let errorCallStack: string = 'error call stack';
let expectedConnection: boolean = false;
let options: IConnectionCompletionOptions = {
params: undefined,
saveTheConnection: false,
showDashboard: false,
showConnectionDialogOnError: false,
showFirewallRuleOnError: true
};
let connectionResult: IConnectionResult = {
connected: expectedConnection,
errorMessage: error,
errorCode: errorCode,
callStack: errorCallStack
};
connect(uri, options, false, connectionProfile, error, errorCode, errorCallStack).then(result => {
assert.equal(result.connected, expectedConnection);
assert.equal(result.errorMessage, connectionResult.errorMessage);
verifyShowFirewallRuleDialog(connectionProfile, false);
verifyShowConnectionDialog(connectionProfile, ConnectionType.default, uri, connectionResult, false);
done();
}).catch(err => {
done(err);
});
});
test('failed firewall rule should open the firewall rule dialog', done => {
handleFirewallRuleResult.canHandleFirewallRule = true;
resolveHandleFirewallRuleDialog = true;
isFirewallRuleAdded = true;
let uri = undefined;
let error: string = 'error';
let errorCode: number = 111;
let expectedConnection: boolean = false;
let expectedError: string = error;
let options: IConnectionCompletionOptions = {
params: undefined,
saveTheConnection: false,
showDashboard: false,
showConnectionDialogOnError: true,
showFirewallRuleOnError: true
};
connect(uri, options, false, connectionProfile, error, errorCode).then(result => {
assert.equal(result.connected, expectedConnection);
assert.equal(result.errorMessage, expectedError);
verifyShowFirewallRuleDialog(connectionProfile, true);
done();
}).catch(err => {
done(err);
});
});
test('failed firewall rule connection should not open the firewall rule dialog if the option is set to false even if connection fails', done => {
handleFirewallRuleResult.canHandleFirewallRule = true;
resolveHandleFirewallRuleDialog = true;
isFirewallRuleAdded = true;
let uri = undefined;
let error: string = 'error when options set to false';
let errorCallStack: string = 'error call stack';
let errorCode: number = 111;
let expectedConnection: boolean = false;
let options: IConnectionCompletionOptions = {
params: undefined,
saveTheConnection: false,
@@ -392,33 +498,119 @@ suite('SQL ConnectionManagementService tests', () => {
showFirewallRuleOnError: false
};
connect(uri, options, false, connectionProfile, error).then(result => {
let connectionResult: IConnectionResult = {
connected: expectedConnection,
errorMessage: error,
errorCode: errorCode,
callStack: errorCallStack
};
connect(uri, options, false, connectionProfile, error, errorCode, errorCallStack).then(result => {
assert.equal(result.connected, expectedConnection);
assert.equal(result.errorMessage, expectedError);
// TODO: not sure how to verify not called
assert.equal(result.errorMessage, connectionResult.errorMessage);
verifyShowFirewallRuleDialog(connectionProfile, false);
verifyShowConnectionDialog(connectionProfile, ConnectionType.default, uri, connectionResult, false);
done();
}).catch(err => {
done(err);
});
});
test('failed firewall rule connection and failed during open firewall rule should open the firewall rule dialog and connection dialog with error', done => {
handleFirewallRuleResult.canHandleFirewallRule = true;
resolveHandleFirewallRuleDialog = false;
isFirewallRuleAdded = true;
test('connect when password is empty and unsaved should open the dialog', done => {
let uri = undefined;
let error: string = 'error when options set to false';
let errorCode: number = 111;
let errorCallStack: string = 'error call stack';
let expectedConnection: boolean = false;
let expectedError: string = undefined;
let options: IConnectionCompletionOptions = {
params: undefined,
saveTheConnection: false,
showDashboard: false,
showConnectionDialogOnError: true,
showFirewallRuleOnError: false
showFirewallRuleOnError: true
};
let connectionResult: IConnectionResult = {
connected: expectedConnection,
errorMessage: error,
errorCode: errorCode,
callStack: errorCallStack
};
connect(uri, options, false, connectionProfile, error, errorCode, errorCallStack).then(result => {
assert.equal(result.connected, expectedConnection);
assert.equal(result.errorMessage, connectionResult.errorMessage);
verifyShowFirewallRuleDialog(connectionProfile, true);
verifyShowConnectionDialog(connectionProfile, ConnectionType.default, uri, connectionResult, true);
done();
}).catch(err => {
done(err);
});
});
test('failed firewall rule connection should open the firewall rule dialog. Then canceled firewall rule dialog should not open connection dialog', done => {
handleFirewallRuleResult.canHandleFirewallRule = true;
resolveHandleFirewallRuleDialog = true;
isFirewallRuleAdded = false;
let uri = undefined;
let error: string = 'error when options set to false';
let errorCallStack: string = 'error call stack';
let errorCode: number = 111;
let expectedConnection: boolean = false;
let options: IConnectionCompletionOptions = {
params: undefined,
saveTheConnection: false,
showDashboard: false,
showConnectionDialogOnError: true,
showFirewallRuleOnError: true
};
let connectionResult: IConnectionResult = {
connected: expectedConnection,
errorMessage: error,
errorCode: errorCode,
callStack: errorCallStack
};
connect(uri, options, false, connectionProfile, error, errorCode, errorCallStack).then(result => {
assert.equal(result.connected, expectedConnection);
assert.equal(result.errorMessage, connectionResult.errorMessage);
verifyShowFirewallRuleDialog(connectionProfile, true);
verifyShowConnectionDialog(connectionProfile, ConnectionType.default, uri, connectionResult, false);
done();
}).catch(err => {
done(err);
});
});
test('connect when password is empty and unsaved should open the dialog', done => {
let uri = undefined;
let expectedConnection: boolean = false;
let options: IConnectionCompletionOptions = {
params: undefined,
saveTheConnection: false,
showDashboard: false,
showConnectionDialogOnError: true,
showFirewallRuleOnError: true
};
let connectionResult: IConnectionResult = {
connected: expectedConnection,
errorMessage: undefined,
errorCode: undefined,
callStack: undefined
};
connect(uri, options, false, connectionProfileWithEmptyUnsavedPassword).then(result => {
assert.equal(result.connected, expectedConnection);
assert.equal(result.errorMessage, expectedError);
verifyShowDialog(connectionProfileWithEmptyUnsavedPassword, ConnectionType.default, uri, expectedError);
assert.equal(result.errorMessage, connectionResult.errorMessage);
verifyShowConnectionDialog(connectionProfileWithEmptyUnsavedPassword, ConnectionType.default, uri, connectionResult);
verifyShowFirewallRuleDialog(connectionProfile, false);
done();
}).catch(err => {
done(err);
@@ -428,19 +620,25 @@ suite('SQL ConnectionManagementService tests', () => {
test('connect when password is empty and saved should not open the dialog', done => {
let uri = undefined;
let expectedConnection: boolean = true;
let expectedError: string = undefined;
let options: IConnectionCompletionOptions = {
params: undefined,
saveTheConnection: false,
showDashboard: false,
showConnectionDialogOnError: true,
showFirewallRuleOnError: false
showFirewallRuleOnError: true
};
let connectionResult: IConnectionResult = {
connected: expectedConnection,
errorMessage: undefined,
errorCode: undefined,
callStack: undefined
};
connect(uri, options, false, connectionProfileWithEmptySavedPassword).then(result => {
assert.equal(result.connected, expectedConnection);
assert.equal(result.errorMessage, expectedError);
verifyShowDialog(connectionProfileWithEmptySavedPassword, ConnectionType.default, uri, expectedError, false);
assert.equal(result.errorMessage, connectionResult.errorMessage);
verifyShowConnectionDialog(connectionProfileWithEmptySavedPassword, ConnectionType.default, uri, connectionResult, false);
done();
}).catch(err => {
done(err);
@@ -450,7 +648,6 @@ suite('SQL ConnectionManagementService tests', () => {
test('connect from editor when empty password when it is required and saved should not open the dialog', done => {
let uri = 'editor 3';
let expectedConnection: boolean = true;
let expectedError: string = undefined;
let options: IConnectionCompletionOptions = {
params: {
connectionType: ConnectionType.editor,
@@ -467,13 +664,20 @@ suite('SQL ConnectionManagementService tests', () => {
saveTheConnection: true,
showDashboard: false,
showConnectionDialogOnError: true,
showFirewallRuleOnError: false
showFirewallRuleOnError: true
};
let connectionResult: IConnectionResult = {
connected: expectedConnection,
errorMessage: undefined,
errorCode: undefined,
callStack: undefined
};
connect(uri, options, false, connectionProfileWithEmptySavedPassword).then(result => {
assert.equal(result.connected, expectedConnection);
assert.equal(result.errorMessage, expectedError);
verifyShowDialog(connectionProfileWithEmptySavedPassword, ConnectionType.editor, uri, expectedError, false);
assert.equal(result.errorMessage, connectionResult.errorMessage);
verifyShowConnectionDialog(connectionProfileWithEmptySavedPassword, ConnectionType.editor, uri, connectionResult, false);
done();
}).catch(err => {
done(err);
@@ -518,7 +722,7 @@ suite('SQL ConnectionManagementService tests', () => {
saveTheConnection: false,
showDashboard: false,
showConnectionDialogOnError: false,
showFirewallRuleOnError: false
showFirewallRuleOnError: true
};
let connectionManagementService = createConnectionManagementService();
let called = false;

View File

@@ -89,7 +89,13 @@ suite('SQL ConnectionStore tests', () => {
storageServiceMock = TypeMoq.Mock.ofType(StorageTestService);
capabilitiesService = TypeMoq.Mock.ofType(CapabilitiesService);
let extensionManagementServiceMock = {
getInstalled: () => {
return Promise.resolve([]);
}
}
capabilitiesService = TypeMoq.Mock.ofType(CapabilitiesService, TypeMoq.MockBehavior.Loose, extensionManagementServiceMock, {});
let capabilities: data.DataProtocolServerCapabilities[] = [];
let connectionProvider: data.ConnectionProviderOptions = {
options: [

View File

@@ -39,7 +39,8 @@ suite('SQL Connection Tree Action tests', () => {
let connectionResult: IConnectionResult = {
connected: true,
errorMessage: undefined,
errorCode: undefined
errorCode: undefined,
callStack: undefined
};
setup(() => {
errorMessageService = TypeMoq.Mock.ofType(ErrorMessageServiceStub, TypeMoq.MockBehavior.Loose);

View File

@@ -3,7 +3,7 @@
* Licensed under the Source EULA. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { ObjectMetadataWrapper } from 'sql/parts/dashboard/widgets/explorer/explorerWidget.component';
import { ObjectMetadataWrapper } from 'sql/parts/dashboard/widgets/explorer/explorerTree';
import { MetadataType } from 'sql/parts/connection/common/connectionManagement';
import * as assert from 'assert';

View File

@@ -255,7 +255,7 @@ suite('Restore Dialog view model tests', () => {
viewModel.readHeaderFromMedia = false;
viewModel.onRestoreFromChanged(true);
assert.equal(true, viewModel.readHeaderFromMedia);
assert.equal('', viewModel.sourceDatabaseName);
assert.equal(undefined, viewModel.sourceDatabaseName);
assert.equal('', viewModel.filePath);
viewModel.sourceDatabaseName = 'sourceDatabase2';

View File

@@ -5,7 +5,7 @@
import { InsightsDialogController } from 'sql/parts/insights/node/insightsDialogController';
import { InsightsDialogModel } from 'sql/parts/insights/common/insightsDialogModel';
import QueryRunner from 'sql/parts/query/execution/queryRunner';
import QueryRunner, { EventType } from 'sql/parts/query/execution/queryRunner';
import { ConnectionManagementService } from 'sql/parts/connection/common/connectionManagementService';
import { IInsightsConfigDetails } from 'sql/parts/dashboard/widgets/insights/interfaces';
import { IConnectionProfile } from 'sql/parts/connection/common/interfaces';
@@ -13,7 +13,7 @@ import { IConnectionProfile } from 'sql/parts/connection/common/interfaces';
import { InstantiationService } from 'vs/platform/instantiation/common/instantiationService';
import { IDbColumn, BatchSummary, QueryExecuteSubsetResult, ResultSetSubset } from 'data';
import { EventEmitter } from 'events';
import { EventEmitter } from 'vs/base/common/eventEmitter';
import { equal } from 'assert';
import { Mock, MockBehavior, It } from 'typemoq';
@@ -47,7 +47,8 @@ suite('Insights Dialog Controller Tests', () => {
undefined,
undefined,
instMoq.object,
connMoq.object
connMoq.object,
undefined
);
let profile: IConnectionProfile = {
@@ -93,9 +94,9 @@ interface IPrimedQueryRunner {
* Returns a mock of query runner than will recreate what a query runner does to return data
*/
function getPrimedQueryRunner(data: string[][], columns: string[]): IPrimedQueryRunner {
let eventEmitter = new EventEmitter();
let emitter = new EventEmitter();
let querymock = Mock.ofType(QueryRunner, MockBehavior.Strict);
querymock.setup(x => x.eventEmitter).returns(x => eventEmitter);
querymock.setup(x => x.addListener(It.isAny(), It.isAny())).returns((event, func) => emitter.addListener(event, func));
querymock.setup(x => x.batchSets).returns(x => {
return <Array<BatchSummary>>[
{
@@ -122,11 +123,11 @@ function getPrimedQueryRunner(data: string[][], columns: string[]): IPrimedQuery
querymock.setup(x => x.runQuery(It.isAnyString())).returns(x => Promise.resolve());
let complete = () => {
eventEmitter.emit('complete');
emitter.emit(EventType.COMPLETE);
};
return {
runner: querymock.object,
complete
};
}
}

View File

@@ -526,7 +526,7 @@ suite('SQL QueryAction Tests', () => {
listItem.onConnected();
// If: I raise a connection changed event for the 'wrong' URI
let eventParams = <IConnectionParams> {
let eventParams = <IConnectionParams>{
connectionProfile: {
databaseName: 'foobarbaz'
},
@@ -552,7 +552,7 @@ suite('SQL QueryAction Tests', () => {
let listItem = new ListDatabasesActionItem(editor.object, undefined, cms.object, null, null, null);
// If: I raise a connection changed event
let eventParams = <IConnectionParams> {
let eventParams = <IConnectionParams>{
connectionProfile: {
databaseName: 'foobarbaz'
},

View File

@@ -8,7 +8,8 @@
import { InstantiationService } from 'vs/platform/instantiation/common/instantiationService';
import { IMessageService } from 'vs/platform/message/common/message';
import { TestMessageService, TestEditorGroupService } from 'vs/workbench/test/workbenchTestServices';
import { IEditorDescriptor, EditorInput } from 'vs/workbench/common/editor';
import { EditorInput } from 'vs/workbench/common/editor';
import { IEditorDescriptor } from 'vs/workbench/browser/editor';
import { TPromise } from 'vs/base/common/winjs.base';
import URI from 'vs/base/common/uri';
import * as DOM from 'vs/base/browser/dom';
@@ -29,6 +30,8 @@ import { TestThemeService } from 'sqltest/stubs/themeTestService';
import * as TypeMoq from 'typemoq';
import * as assert from 'assert';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { BaseEditor } from 'vs/workbench/browser/parts/editor/baseEditor';
suite('SQL QueryEditor Tests', () => {
let queryModelService: QueryModelService;
@@ -55,7 +58,6 @@ suite('SQL QueryEditor Tests', () => {
editorDescriptorService.object,
undefined,
undefined,
undefined,
undefined);
};
@@ -101,7 +103,8 @@ suite('SQL QueryEditor Tests', () => {
let descriptor: IEditorDescriptor = {
getId: function (): string { return 'id'; },
getName: function (): string { return 'name'; },
describes: function (obj: any): boolean { return true; }
describes: function (obj: any): boolean { return true; },
instantiate(instantiationService: IInstantiationService): BaseEditor { return undefined; }
};
editorDescriptorService = TypeMoq.Mock.ofType(EditorDescriptorService, TypeMoq.MockBehavior.Loose);
editorDescriptorService.setup(x => x.getEditor(TypeMoq.It.isAny())).returns(() => descriptor);
@@ -109,14 +112,14 @@ suite('SQL QueryEditor Tests', () => {
// Create a QueryInput
let filePath = 'someFile.sql';
let uri: URI = URI.parse(filePath);
let fileInput = new UntitledEditorInput(uri, false, '', '', '', instantiationService.object, undefined, undefined, undefined);
let fileInput = new UntitledEditorInput(uri, false, '', '', '', instantiationService.object, undefined, undefined, undefined, undefined);
let queryResultsInput: QueryResultsInput = new QueryResultsInput(uri.fsPath);
queryInput = new QueryInput('first', 'first', fileInput, queryResultsInput, undefined, undefined, undefined, undefined);
// Create a QueryInput to compare to the previous one
let filePath2 = 'someFile2.sql';
let uri2: URI = URI.parse(filePath2);
let fileInput2 = new UntitledEditorInput(uri2, false, '', '', '', instantiationService.object, undefined, undefined, undefined);
let fileInput2 = new UntitledEditorInput(uri2, false, '', '', '', instantiationService.object, undefined, undefined, undefined, undefined);
let queryResultsInput2: QueryResultsInput = new QueryResultsInput(uri2.fsPath);
queryInput2 = new QueryInput('second', 'second', fileInput2, queryResultsInput2, undefined, undefined, undefined, undefined);
@@ -154,6 +157,7 @@ suite('SQL QueryEditor Tests', () => {
done();
});
/*
test('setInput creates SQL components', (done) => {
let assertInput = function () {
// The taskbar SQL, and parent should be created
@@ -213,8 +217,6 @@ suite('SQL QueryEditor Tests', () => {
editorDescriptorService.object,
editorGroupService.object,
undefined,
undefined,
undefined,
undefined);
editor.create(parentBuilder);
@@ -302,6 +304,7 @@ suite('SQL QueryEditor Tests', () => {
.then(assertFirstInputIsAddedBack) // the inputs should not match, and the second input should be removed from the DOM
.then(() => done(), (err) => done(err));
});
*/
suite('Action Tests', () => {
let queryActionInstantiationService: TypeMoq.Mock<InstantiationService>;
@@ -339,7 +342,7 @@ suite('SQL QueryEditor Tests', () => {
return new RunQueryAction(undefined, undefined, undefined);
});
let fileInput = new UntitledEditorInput(URI.parse('testUri'), false, '', '', '', instantiationService.object, undefined, undefined, undefined);
let fileInput = new UntitledEditorInput(URI.parse('testUri'), false, '', '', '', instantiationService.object, undefined, undefined, undefined, undefined);
queryModelService = TypeMoq.Mock.ofType(QueryModelService, TypeMoq.MockBehavior.Loose, undefined, undefined);
queryModelService.callBase = true;
queryInput = new QueryInput(

View File

@@ -24,7 +24,7 @@ suite('ServerTreeView onAddConnectionProfile handler tests', () => {
let instantiationService = new TestInstantiationService();
let mockConnectionManagementService = TypeMoq.Mock.ofType(ConnectionManagementService, TypeMoq.MockBehavior.Strict, {}, {});
mockConnectionManagementService.setup(x => x.getConnectionGroups()).returns(x => []);
serverTreeView = new ServerTreeView(mockConnectionManagementService.object, instantiationService, undefined, undefined, undefined);
serverTreeView = new ServerTreeView(mockConnectionManagementService.object, instantiationService, undefined, undefined, undefined, undefined);
let tree = <Tree>{
clearSelection() { },
getSelection() { },

View File

@@ -9,7 +9,6 @@ import * as assert from 'assert';
import * as data from 'data';
import * as TypeMoq from 'typemoq';
import AccountStore from 'sql/services/accountManagement/accountStore';
import { SqlOAuthTestService } from 'sqltest/stubs/sqlOauthServiceStub';
import { AccountDialogController } from 'sql/parts/accountManagement/accountDialog/accountDialogController';
import { AccountManagementService } from 'sql/services/accountManagement/accountManagementService';
import { AccountAdditionResult, AccountProviderAddedEventParams, UpdateAccountListEventParams } from 'sql/services/accountManagement/eventTypes';
@@ -35,7 +34,7 @@ const account: data.Account = {
},
displayInfo: {
displayName: 'Test Account 1',
contextualLogo: {light: '', dark: ''},
accountType: 'test',
contextualDisplayName: 'Azure Account'
},
isStale: false,
@@ -56,6 +55,81 @@ suite('Account Management Service Tests:', () => {
assert.ok(ams.updateAccountListEvent);
});
test('Account Updated - account added', done => {
// Setup:
// ... Create account management service and to mock up the store
let state = getTestState();
state.mockAccountStore.setup(x => x.addOrUpdate(TypeMoq.It.isAny()))
.returns(account => Promise.resolve(<AccountAdditionResult>{
accountModified: false,
accountAdded: true,
changedAccount: account
}));
state.mockAccountStore.setup(x => x.remove(TypeMoq.It.isAny()))
.returns(() => Promise.resolve(true));
// ... Register a account provider with the management service
let mockProvider = TypeMoq.Mock.ofType<data.AccountProvider>(AccountProviderStub);
mockProvider.setup(x => x.clear(TypeMoq.It.isAny())).returns(() => Promise.resolve());
state.accountManagementService._providers[hasAccountProvider.id] = {
accounts: [account],
provider: mockProvider.object,
metadata: hasAccountProvider
};
// If: I update an account that doesn't exist
state.accountManagementService.accountUpdated(account)
.then(() => {
// Then: Make sure the mocked methods are called
state.mockAccountStore.verify(x => x.addOrUpdate(TypeMoq.It.isAny()), TypeMoq.Times.once());
state.mockAccountStore.verify(x => x.remove(TypeMoq.It.isAny()), TypeMoq.Times.once());
})
.then(
() => done(),
err => done(err)
);
});
test('Account Updated - account modified', done => {
// Setup:
// ... Create account management service and to mock up the store
let state = getTestState();
state.mockAccountStore.setup(x => x.addOrUpdate(TypeMoq.It.isAny()))
.returns(account => Promise.resolve(<AccountAdditionResult> {
accountModified: true,
accountAdded: false,
changedAccount: account
}));
// ... Register a account provider with the management service
let mockProvider = TypeMoq.Mock.ofType<data.AccountProvider>(AccountProviderStub);
mockProvider.setup(x => x.clear(TypeMoq.It.isAny())).returns(() => Promise.resolve());
state.accountManagementService._providers[hasAccountProvider.id] = {
accounts: [account],
provider: mockProvider.object,
metadata: hasAccountProvider
};
// If: I update an account that exists
state.accountManagementService.accountUpdated(account)
.then(() => {
// Then:
// ... The mocked method was called
state.mockAccountStore.verify(x => x.addOrUpdate(TypeMoq.It.isAny()), TypeMoq.Times.once());
// ... The account list was updated
state.eventVerifierUpdate.assertFiredWithVerify((params: UpdateAccountListEventParams) => {
assert.equal(params.providerId, hasAccountProvider.id);
assert.ok(Array.isArray(params.accountList));
assert.equal(params.accountList.length, 1);
});
})
.then(
() => done(),
err => done(err)
);
});
test('Add account - provider exists, account does not exist', done => {
// Setup:
// ... Create account management service with a provider
@@ -77,7 +151,7 @@ suite('Account Management Service Tests:', () => {
// If: I ask to add an account
return state.accountManagementService.addAccount(hasAccountProvider.id)
.then(result => {
.then(() => {
// Then:
// ... The provider should have been prompted
mockProvider.verify(x => x.prompt(), TypeMoq.Times.once());
@@ -92,13 +166,10 @@ suite('Account Management Service Tests:', () => {
assert.equal(param.accountList.length, 1);
assert.equal(param.accountList[0], account);
});
// ... The returned account should be the new one
assert.equal(result, account);
})
.then(
() => done(),
err => done(err)
() => done(),
err => done(err)
);
});
@@ -123,7 +194,7 @@ suite('Account Management Service Tests:', () => {
// If: I ask to add an account
return state.accountManagementService.addAccount(hasAccountProvider.id)
.then(result => {
.then(() => {
// Then:
// ... The provider should have been prompted
mockProvider.verify(x => x.prompt(), TypeMoq.Times.once());
@@ -138,13 +209,10 @@ suite('Account Management Service Tests:', () => {
assert.equal(param.accountList.length, 1);
assert.equal(param.accountList[0], account);
});
// ... The returned account should be the new one
assert.equal(result, account);
})
.then(
() => done(),
err => done(err)
() => done(),
err => done(err)
);
});
@@ -156,12 +224,42 @@ suite('Account Management Service Tests:', () => {
// Then: It should be rejected
ams.addAccount('doesNotExist')
.then(
() => done('Promise resolved when it should have rejected'),
() => done()
() => done('Promise resolved when it should have rejected'),
() => done()
);
});
test('Add account - provider exists, provider fails', done => {
// Setup: Create account management service with a provider
let state = getTestState();
let mockProvider = getFailingMockAccountProvider(false);
state.accountManagementService.registerProvider(noAccountProvider, mockProvider.object);
// If: I ask to add an account and the user cancels
// Then: Nothing should have happened and the promise should be resolved
return state.accountManagementService.addAccount(noAccountProvider.id)
.then(
() => done('Add account promise resolved when it should have rejected'),
() => done()
);
});
test('Add account - provider exists, user cancelled', done => {
// Setup: Create account management service with a provider
let state = getTestState();
let mockProvider = getFailingMockAccountProvider(true);
state.accountManagementService.registerProvider(noAccountProvider, mockProvider.object);
// If: I ask to add an account and the user cancels
// Then: Nothing should have happened and the promise should be resolved
return state.accountManagementService.addAccount(noAccountProvider.id)
.then(
() => done(),
err => done(err)
);
});
test('Get account provider metadata - providers exist', done => {
// Setup: Create account management service with a provider
let state = getTestState();
@@ -180,8 +278,8 @@ suite('Account Management Service Tests:', () => {
assert.equal(result[0], noAccountProvider);
})
.then(
() => done(),
err => done(err)
() => done(),
err => done(err)
);
});
@@ -197,8 +295,8 @@ suite('Account Management Service Tests:', () => {
assert.equal(result.length, 0);
})
.then(
() => done(),
err => done(err)
() => done(),
err => done(err)
);
});
@@ -210,8 +308,8 @@ suite('Account Management Service Tests:', () => {
// Then: It should be rejected
ams.getAccountsForProvider('doesNotExist')
.then(
() => done('Promise resolved when it should have rejected'),
() => done()
() => done('Promise resolved when it should have rejected'),
() => done()
);
});
@@ -232,8 +330,8 @@ suite('Account Management Service Tests:', () => {
assert.equal(result.length, 0);
})
.then(
() => done(),
err => done(err)
() => done(),
err => done(err)
);
});
@@ -253,8 +351,8 @@ suite('Account Management Service Tests:', () => {
assert.equal(result, accountList);
})
.then(
() => done(),
err => done(err)
() => done(),
err => done(err)
);
});
@@ -276,7 +374,7 @@ suite('Account Management Service Tests:', () => {
// If: I remove an account that exists
state.accountManagementService.removeAccount(account.key)
.then( result => {
.then(result => {
// Then:
// ... I should have gotten true back
assert.ok(result);
@@ -295,8 +393,8 @@ suite('Account Management Service Tests:', () => {
});
})
.then(
() => done(),
err => done(err)
() => done(),
err => done(err)
);
});
@@ -317,7 +415,7 @@ suite('Account Management Service Tests:', () => {
};
// If: I remove an account that doesn't exist
let accountKey = {providerId: noAccountProvider.id, accountId: 'foobar'};
let accountKey = { providerId: noAccountProvider.id, accountId: 'foobar' };
state.accountManagementService.removeAccount(accountKey)
.then(result => {
// Then:
@@ -334,8 +432,8 @@ suite('Account Management Service Tests:', () => {
state.eventVerifierUpdate.assertNotFired();
})
.then(
() => done(),
err => done(err)
() => done(),
err => done(err)
);
});
@@ -361,8 +459,8 @@ suite('Account Management Service Tests:', () => {
mockDialogController.verify(x => x.openAccountDialog(), TypeMoq.Times.once());
})
.then(
() => done(),
err => done(err)
() => done(),
err => done(err)
);
});
@@ -389,13 +487,13 @@ suite('Account Management Service Tests:', () => {
mockDialogController.verify(x => x.openAccountDialog(), TypeMoq.Times.exactly(2));
})
.then(
() => done(),
err => done(err)
() => done(),
err => done(err)
);
});
// test('Perform oauth - success', done => {
// TODO: implement this test properly once we remove direct IPC calls
// TODO: implement this test properly once we remove direct IPC calls (see https://github.com/Microsoft/carbon/issues/2091)
// });
test('Register provider - success', done => {
@@ -426,8 +524,8 @@ suite('Account Management Service Tests:', () => {
});
})
.then(
() => done(),
err => done(err)
() => done(),
err => done(err)
);
});
@@ -439,14 +537,14 @@ suite('Account Management Service Tests:', () => {
// ... Register a provider to remove
let mockProvider = getMockAccountProvider();
mocks.accountManagementService.registerProvider(noAccountProvider, mockProvider.object)
.then((success) => {
// If: I remove an account provider
mocks.accountManagementService.unregisterProvider(noAccountProvider);
.then((success) => {
// If: I remove an account provider
mocks.accountManagementService.unregisterProvider(noAccountProvider);
// Then: The provider removed event should have fired
mocks.eventVerifierProviderRemoved.assertFired(noAccountProvider);
}, error => {
}).then(() => done(), err => done(err));
}, error => {
}).then(() => done(), err => done(err));
});
});
@@ -468,7 +566,7 @@ function getTestState(): AccountManagementState {
let mockMemento = {};
// Create the account management service
let ams = new AccountManagementService(mockMemento, mockInstantiationService.object, null, new SqlOAuthTestService());
let ams = new AccountManagementService(mockMemento, mockInstantiationService.object, null, null);
// Wire up event handlers
let evUpdate = new EventVerifierSingle<UpdateAccountListEventParams>();
@@ -498,6 +596,27 @@ function getMockAccountProvider(): TypeMoq.Mock<data.AccountProvider> {
return mockProvider;
}
function getFailingMockAccountProvider(cancel: boolean): TypeMoq.Mock<data.AccountProvider> {
let mockProvider = TypeMoq.Mock.ofType<data.AccountProvider>(AccountProviderStub);
mockProvider.setup(x => x.clear(TypeMoq.It.isAny()))
.returns(() => Promise.resolve());
mockProvider.setup(x => x.initialize(TypeMoq.It.isAny()))
.returns(param => Promise.resolve(param));
mockProvider.setup(x => x.prompt())
.returns(() => {
return cancel
? Promise.reject(<data.UserCancelledSignInError>{userCancelledSignIn: true}).then()
: Promise.reject(new Error()).then();
});
mockProvider.setup(x => x.refresh(TypeMoq.It.isAny()))
.returns(() => {
return cancel
? Promise.reject(<data.UserCancelledSignInError>{userCancelledSignIn: true}).then()
: Promise.reject(new Error()).then();
});
return mockProvider;
}
interface AccountManagementState {
accountManagementService: AccountManagementService;
instantiationService: TypeMoq.Mock<InstantiationService>;
@@ -505,4 +624,4 @@ interface AccountManagementState {
eventVerifierUpdate: EventVerifierSingle<UpdateAccountListEventParams>;
eventVerifierProviderAdded: EventVerifierSingle<AccountProviderAddedEventParams>;
eventVerifierProviderRemoved: EventVerifierSingle<data.AccountProviderMetadata>;
}
}

View File

@@ -8,7 +8,7 @@
import * as assert from 'assert';
import * as data from 'data';
import AccountStore from 'sql/services/accountManagement/accountStore';
import {EventVerifierSingle} from 'sqltest/utils/eventVerifier';
import { EventVerifierSingle } from 'sqltest/utils/eventVerifier';
suite('Account Store Tests', () => {
test('AddOrUpdate - Uninitialized memento', done => {
@@ -31,8 +31,8 @@ suite('Account Store Tests', () => {
assertAccountEqual(memento[AccountStore.MEMENTO_KEY][0], account1);
})
.then(
() => done(),
e => done(e)
() => done(),
e => done(e)
);
});
@@ -57,8 +57,8 @@ suite('Account Store Tests', () => {
assertAccountEqual(memento[AccountStore.MEMENTO_KEY][0], account1);
})
.then(
() => done(),
e => done(e)
() => done(),
e => done(e)
);
});
@@ -88,8 +88,8 @@ suite('Account Store Tests', () => {
assertAccountEqual(memento[AccountStore.MEMENTO_KEY][1], param);
})
.then(
() => done(),
e => done(e)
() => done(),
e => done(e)
);
});
@@ -110,8 +110,8 @@ suite('Account Store Tests', () => {
assert.equal(Object.keys(memento).length, 0);
})
.then(
() => done(),
e => done(e)
() => done(),
e => done(e)
);
});
@@ -129,8 +129,8 @@ suite('Account Store Tests', () => {
assert.equal(result.length, 0);
})
.then(
() => done(),
e => done(e)
() => done(),
e => done(e)
);
});
@@ -147,8 +147,8 @@ suite('Account Store Tests', () => {
assert.equal(result.length, 0);
})
.then(
() => done(),
e => done(e)
() => done(),
e => done(e)
);
});
@@ -167,8 +167,8 @@ suite('Account Store Tests', () => {
assertAccountEqual(result[1], memento[AccountStore.MEMENTO_KEY][1]);
})
.then(
() => done(),
e => done(e)
() => done(),
e => done(e)
);
});
@@ -189,8 +189,8 @@ suite('Account Store Tests', () => {
assert.equal(Object.keys(memento).length, 0);
})
.then(
() => done(),
e => done(e)
() => done(),
e => done(e)
);
});
@@ -208,8 +208,8 @@ suite('Account Store Tests', () => {
assert.equal(result.length, 0);
})
.then(
() => done(),
e => done(e)
() => done(),
e => done(e)
);
});
@@ -228,8 +228,8 @@ suite('Account Store Tests', () => {
assertAccountEqual(result[1], memento[AccountStore.MEMENTO_KEY][1]);
})
.then(
() => done(),
e => done(e)
() => done(),
e => done(e)
);
});
@@ -250,8 +250,8 @@ suite('Account Store Tests', () => {
assert.equal(memento[AccountStore.MEMENTO_KEY].length, 0);
})
.then(
() => done(),
e => done(e)
() => done(),
e => done(e)
);
});
@@ -262,7 +262,7 @@ suite('Account Store Tests', () => {
let as = new AccountStore(memento);
// If: I remove an account that doesn't exist
as.remove({providerId: 'cloudyCloud', accountId: 'testyTest'})
as.remove({ providerId: 'cloudyCloud', accountId: 'testyTest' })
.then(result => {
// Then:
// ... I should get back false (no account removed)
@@ -273,8 +273,8 @@ suite('Account Store Tests', () => {
assert.equal(memento[AccountStore.MEMENTO_KEY].length, 0);
})
.then(
() => done(),
e => done(e)
() => done(),
e => done(e)
);
});
@@ -296,8 +296,8 @@ suite('Account Store Tests', () => {
assertAccountEqual(memento[AccountStore.MEMENTO_KEY][0], account2);
})
.then(
() => done(),
e => done(e)
() => done(),
e => done(e)
);
});
@@ -325,8 +325,8 @@ suite('Account Store Tests', () => {
updateCallback.assertNotFired();
})
.then(
() => done(),
e => done(e)
() => done(),
e => done(e)
);
});
@@ -340,7 +340,7 @@ suite('Account Store Tests', () => {
let updateCallback = new EventVerifierSingle<data.Account>();
// If: I update an account that doesn't exist
as.update({accountId: 'testyTest', providerId: 'cloudyCloud'}, updateCallback.eventHandler)
as.update({ accountId: 'testyTest', providerId: 'cloudyCloud' }, updateCallback.eventHandler)
.then(result => {
// Then:
// ... I should get back false (account did not change)
@@ -354,8 +354,8 @@ suite('Account Store Tests', () => {
updateCallback.assertNotFired();
})
.then(
() => done(),
e => done(e)
() => done(),
e => done(e)
);
});
@@ -388,8 +388,8 @@ suite('Account Store Tests', () => {
assertAccountEqual(memento[AccountStore.MEMENTO_KEY][1], account2);
})
.then(
() => done(),
e => done(e)
() => done(),
e => done(e)
);
});
@@ -404,7 +404,7 @@ const account1 = <data.Account>{
},
displayInfo: {
displayName: 'Test Account 1',
//contextualLogo: {light: '', dark: ''},
accountType: 'test',
contextualDisplayName: 'Azure Account'
},
isStale: false
@@ -417,7 +417,7 @@ const account2 = <data.Account>{
},
displayInfo: {
displayName: 'Test Account 2',
//contextualLogo: {light: '', dark: ''},
accountType: 'test',
contextualDisplayName: 'Azure Account'
},
isStale: false
@@ -435,7 +435,7 @@ function assertAccountEqual(a: data.Account, b: data.Account) {
assert.equal(a.key.accountId, b.key.accountId);
assert.equal(a.displayInfo.contextualDisplayName, b.displayInfo.contextualDisplayName);
//assert.equal(a.displayInfo.contextualLogo, b.displayInfo.contextualLogo);
assert.equal(a.displayInfo.accountType, b.displayInfo.accountType);
assert.equal(a.displayInfo.displayName, b.displayInfo.displayName);
assert.equal(a.isStale, b.isStale);

View File

@@ -14,11 +14,31 @@ import { TPromise } from 'vs/base/common/winjs.base';
export class AccountManagementTestService implements IAccountManagementService {
_serviceBrand: any;
public get addAccountProviderEvent(): Event<AccountProviderAddedEventParams> {return () => {return undefined;};}
public get removeAccountProviderEvent(): Event<data.AccountProviderMetadata> {return () => {return undefined;};}
public get updateAccountListEvent(): Event<UpdateAccountListEventParams> {return () => {return undefined;};}
public get addAccountProviderEvent(): Event<AccountProviderAddedEventParams> { return () => { return undefined; }; }
public get removeAccountProviderEvent(): Event<data.AccountProviderMetadata> { return () => { return undefined; }; }
public get updateAccountListEvent(): Event<UpdateAccountListEventParams> { return () => { return undefined; }; }
addAccount(providerId: string): Thenable<data.Account> {
accountUpdated(account: data.Account): Thenable<void> {
return undefined;
}
addAccount(providerId: string): Thenable<void> {
return undefined;
}
beginAutoOAuthDeviceCode(title: string, message: string, userCode: string, uri: string): Thenable<void> {
return undefined;
}
cancelAutoOAuthDeviceCode(providerId: string): void {
return undefined;
}
endAutoOAuthDeviceCode(): void {
return undefined;
}
copyUserCodeAndOpenBrowser(userCode: string, uri: string): void {
return undefined;
}
@@ -38,11 +58,11 @@ export class AccountManagementTestService implements IAccountManagementService {
return undefined;
}
openAccountListDialog(): TPromise<any> {
refreshAccount(account: data.Account): Thenable<data.Account> {
return undefined;
}
performOAuthAuthorization(url: string, silent: boolean): Thenable<string> {
openAccountListDialog(): TPromise<any> {
return undefined;
}
@@ -60,6 +80,10 @@ export class AccountManagementTestService implements IAccountManagementService {
}
export class AccountProviderStub implements data.AccountProvider {
autoOAuthCancelled(): Thenable<void> {
return Promise.resolve();
}
clear(account: data.AccountKey): Thenable<void> {
return Promise.resolve();
}

View File

@@ -5,7 +5,7 @@
'use strict';
import {
IConnectionDialogService, IConnectionManagementService, INewConnectionParams
IConnectionDialogService, IConnectionManagementService, INewConnectionParams, IConnectionResult
} from 'sql/parts/connection/common/connectionManagement';
import { TPromise } from 'vs/base/common/winjs.base';
import { IConnectionProfile } from 'sql/parts/connection/common/interfaces';
@@ -14,7 +14,7 @@ export class ConnectionDialogTestService implements IConnectionDialogService {
_serviceBrand: any;
public showDialog(connectionManagementService: IConnectionManagementService,
params: INewConnectionParams, model: IConnectionProfile, error?: string): TPromise<void> {
params: INewConnectionParams, model: IConnectionProfile, connectionResult?: IConnectionResult): TPromise<void> {
let none: void;
return TPromise.as(none);
}

View File

@@ -35,7 +35,7 @@ export class TestConnectionManagementService implements IConnectionManagementSer
}
showConnectionDialog(params?: INewConnectionParams, model?: IConnectionProfile, error?: string): Promise<void> {
showConnectionDialog(params?: INewConnectionParams, model?: IConnectionProfile, connectionResult?: IConnectionResult): Promise<void> {
return undefined;
}
@@ -83,6 +83,10 @@ export class TestConnectionManagementService implements IConnectionManagementSer
return;
}
public clearRecentConnection(connectionProfile: ConnectionProfile): void {
return;
}
getUnsavedConnections(): ConnectionProfile[] {
return [];
}
@@ -141,7 +145,7 @@ export class TestConnectionManagementService implements IConnectionManagementSer
connect(connection: IConnectionProfile, uri: string, options?: IConnectionCompletionOptions, callbacks?: IConnectionCallbacks): Promise<IConnectionResult> {
return new Promise<IConnectionResult>((resolve, reject) => {
resolve({ connected: true, errorMessage: undefined, errorCode: undefined });
resolve({ connected: true, errorMessage: undefined, errorCode: undefined, callStack: undefined });
});
}

View File

@@ -5,13 +5,12 @@
'use strict';
import { createDecorator, ServiceIdentifier } from 'vs/platform/instantiation/common/instantiation';
import { ServiceIdentifier, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { Position, IEditorInput } from 'vs/platform/editor/common/editor';
import { IEditorStacksModel, IEditorGroup, EditorInput } from 'vs/workbench/common/editor';
import { IEditorStacksModel, IEditorGroup, EditorInput, IEditorOpeningEvent } from 'vs/workbench/common/editor';
import Event from 'vs/base/common/event';
import { ITabOptions, GroupArrangement, GroupOrientation } from 'vs/workbench/services/group/common/groupService';
import { IEditorGroupService, IMoveOptions } from 'vs/workbench/services/group/common/groupService';
import { EditorGroup } from "vs/workbench/common/editor/editorStacksModel";
import { IEditorTabOptions, GroupArrangement, GroupOrientation, IEditorGroupService, IMoveOptions } from 'vs/workbench/services/group/common/groupService';
import { EditorGroup } from 'vs/workbench/common/editor/editorStacksModel';
export class EditorGroupTestService implements IEditorGroupService {
_serviceBrand: ServiceIdentifier<any>;
@@ -21,6 +20,14 @@ export class EditorGroupTestService implements IEditorGroupService {
*/
onEditorsChanged: Event<void>;
onEditorOpening: Event<IEditorOpeningEvent>;
onEditorGroupMoved: Event<void>;
invokeWithinEditorContext<T>(fn: (accessor: ServicesAccessor) => T): T {
return undefined;
}
/**
* Emitted when opening an editor fails.
*/
@@ -39,7 +46,7 @@ export class EditorGroupTestService implements IEditorGroupService {
/**
* Emitted when tab options changed.
*/
onTabOptionsChanged: Event<ITabOptions>;
onTabOptionsChanged: Event<IEditorTabOptions>;
/**
* Keyboard focus the editor group at the provided position.
@@ -108,7 +115,7 @@ export class EditorGroupTestService implements IEditorGroupService {
/**
* Returns true if tabs are shown, false otherwise.
*/
getTabOptions(): ITabOptions {
getTabOptions(): IEditorTabOptions {
return undefined;
}

View File

@@ -6,7 +6,8 @@
'use strict';
import Severity from 'vs/base/common/severity';
import { IConfirmation, IMessageService, IMessageWithAction } from 'vs/platform/message/common/message';
import { IConfirmation, IMessageService, IMessageWithAction, IConfirmationResult } from 'vs/platform/message/common/message';
import { TPromise } from 'vs/base/common/winjs.base';
export class MessageServiceStub implements IMessageService{
_serviceBrand: any;
@@ -24,7 +25,14 @@ export class MessageServiceStub implements IMessageService{
return undefined;
}
confirm(confirmation: IConfirmation): boolean {
confirm(confirmation: IConfirmation): TPromise<IConfirmationResult> {
return undefined;
}
/**
* Ask the user for confirmation.
*/
confirmSync(confirmation: IConfirmation): boolean {
return undefined;
}
}

View File

@@ -0,0 +1,32 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the Source EULA. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as data from 'data';
import { IHandleFirewallRuleResult, IResourceProviderService } from 'sql/parts/accountManagement/common/interfaces';
import { IConnectionProfile } from 'sql/parts/connection/common/interfaces';
export class ResourceProviderStub implements IResourceProviderService {
_serviceBrand: any;
registerProvider(providerId: string, provider: data.ResourceProvider) {
}
unregisterProvider(ProviderId: string) {
}
createFirewallRule(selectedAccount: data.Account, firewallruleInfo: data.FirewallRuleInfo, resourceProviderId: string): Promise<data.CreateFirewallRuleResponse> {
return undefined;
}
handleFirewallRule(errorCode: number, errorMessage: string, connectionTypeId: string): Promise<IHandleFirewallRuleResult> {
return undefined;
}
showFirewallRuleDialog(connection: IConnectionProfile, ipAddress: string, resourceProviderId: string): Promise<boolean> {
return undefined;
}
}

View File

@@ -1,18 +0,0 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the Source EULA. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import { ISqlOAuthService } from 'sql/common/sqlOAuthService';
export class SqlOAuthTestService implements ISqlOAuthService {
_serviceBrand: any;
performOAuthAuthorization(eventId: string, url: string, silent: boolean): void {
}
registerOAuthCallback(handler: (event, args) => void): void {
}
}

View File

@@ -9,7 +9,7 @@ import { IEditorService, IEditor, IEditorInput, IEditorOptions, ITextEditorOptio
from 'vs/platform/editor/common/editor';
import { TPromise } from 'vs/base/common/winjs.base';
import { BaseEditor } from 'vs/workbench/browser/parts/editor/baseEditor';
import { EditorInput, EditorOptions, IFileEditorInput, TextEditorOptions, IEditorRegistry, Extensions, SideBySideEditorInput } from 'vs/workbench/common/editor';
import { EditorInput, EditorOptions, IFileEditorInput, TextEditorOptions, Extensions, SideBySideEditorInput } from 'vs/workbench/common/editor';
export class WorkbenchEditorTestService implements IWorkbenchEditorService {
_serviceBrand: ServiceIdentifier<any>;

View File

@@ -5,76 +5,60 @@
'use strict';
import { IWorkspaceConfigurationService } from 'vs/workbench/services/configuration/common/configuration';
import {
IConfigurationValue, IConfigurationData, IConfigurationKeys,
IConfigurationServiceEvent, IConfigurationValues } from 'vs/platform/configuration/common/configuration';
import { IConfigurationData, IConfigurationOverrides, ConfigurationTarget } from 'vs/platform/configuration/common/configuration';
import { IConfigurationValue } from 'vs/workbench/services/configuration/node/configurationEditingService';
import { IConfigurationChangeEvent } from 'vs/platform/configuration/common/configuration';
import { TPromise } from 'vs/base/common/winjs.base';
import Event from 'vs/base/common/event';
import { IWorkspaceFolder } from 'vs/platform/workspace/common/workspace';
export class WorkspaceConfigurationTestService implements IWorkspaceConfigurationService {
_serviceBrand: any;
onDidChangeConfiguration: Event<IConfigurationChangeEvent>;
getConfigurationData<T>(): IConfigurationData<T> {
return undefined;
getConfigurationData(): IConfigurationData { return undefined; }
getConfiguration<T>(): T
getConfiguration<T>(section: string): T
getConfiguration<T>(overrides: IConfigurationOverrides): T
getConfiguration<T>(section: string, overrides: IConfigurationOverrides): T
getConfiguration(arg1?: any, arg2?: any): any {
return TPromise.as(null);
}
/**
* Returns untrusted configuration keys for the current workspace.
*/
getUnsupportedWorkspaceKeys(): string[] {
return [];
getValue<T>(key: string, overrides?: IConfigurationOverrides): T { return undefined; }
updateValue(key: string, value: any): TPromise<void>
updateValue(key: string, value: any, overrides: IConfigurationOverrides): TPromise<void>
updateValue(key: string, value: any, target: ConfigurationTarget): TPromise<void>
updateValue(key: string, value: any, overrides: IConfigurationOverrides, target: ConfigurationTarget): TPromise<void>
updateValue(key: string, value: any, overrides: IConfigurationOverrides, target: ConfigurationTarget, donotNotifyError: boolean): TPromise<void>
updateValue(key: string, value: any, arg3?: any, arg4?: any, donotNotifyError?: any): TPromise<void> {
return TPromise.as(null);
}
/**
* Returns iff the workspace has configuration or not.
*/
hasWorkspaceConfiguration(): boolean {
return true;
reloadConfiguration(folder?: IWorkspaceFolder, key?: string): TPromise<void> {
return TPromise.as(null);
}
/**
* Returns untrusted configuration keys for the current workspace.
*/
getUntrustedConfigurations(): string[] {
return [];
}
inspect<T>(key: string): {
default: T,
user: T,
workspace: T,
workspaceFolder: T,
memory?: T,
value: T,
} { return undefined; }
/**
* Returns if the user explicitly configured to not trust the current workspace.
*/
isExplicitlyUntrusted(): boolean {
return true;
}
keys(): {
default: string[];
user: string[];
workspace: string[];
workspaceFolder: string[];
memory?: string[];
} { return undefined; }
/**
* Override for the IConfigurationService#lookup() method that adds information about workspace settings.
*/
lookup<T>(key: string): IConfigurationValue<T> {
return undefined;
}
getConfiguration<T>(section?: string): T {
return undefined;
}
reloadConfiguration<T>(section?: string): TPromise<T> {
return undefined;
}
/**
* Override for the IConfigurationService#keys() method that adds information about workspace settings.
*/
keys(): IConfigurationKeys {
return undefined;
}
/**
* Returns the defined values of configurations in the different scopes.
*/
values(): IConfigurationValues {
return undefined;
}
onDidUpdateConfiguration: Event<IConfigurationServiceEvent>;
}
getUnsupportedWorkspaceKeys(): string[] { return undefined; }
}

View File

@@ -55,7 +55,7 @@ suite('ExtHostAccountManagement', () => {
displayInfo: {
displayName: 'Test Account',
contextualDisplayName: 'Test Kind Of Account',
contextualLogo: { light: '', dark: '' }
accountType: 'test'
},
isStale: false
};

View File

@@ -52,78 +52,59 @@ suite('ExtHostDataProtocol', function () {
suiteSetup(() => {
threadService = new TestThreadService();
let instantiationService = new TestInstantiationService();
instantiationService.stub(IThreadService, threadService);
instantiationService.stub(IMarkerService, MarkerService);
instantiationService.stub(IHeapService, {
_serviceBrand: undefined,
trackRecursive(args) {
// nothing
return args;
}
});
// threadService = new TestThreadService();
// let instantiationService = new TestInstantiationService();
// instantiationService.stub(IThreadService, threadService);
// instantiationService.stub(IMarkerService, MarkerService);
// instantiationService.stub(IHeapService, {
// _serviceBrand: undefined,
// trackRecursive(args) {
// // nothing
// return args;
// }
// });
originalErrorHandler = errorHandler.getUnexpectedErrorHandler();
setUnexpectedErrorHandler(() => { });
// originalErrorHandler = errorHandler.getUnexpectedErrorHandler();
// setUnexpectedErrorHandler(() => { });
const extHostDocumentsAndEditors = new ExtHostDocumentsAndEditors(threadService);
extHostDocumentsAndEditors.$acceptDocumentsAndEditorsDelta({
addedDocuments: [{
isDirty: false,
versionId: model.getVersionId(),
modeId: model.getLanguageIdentifier().language,
url: model.uri,
lines: model.getValue().split(model.getEOL()),
EOL: model.getEOL(),
}]
});
const extHostDocuments = new ExtHostDocuments(threadService, extHostDocumentsAndEditors);
threadService.set(ExtHostContext.ExtHostDocuments, extHostDocuments);
// const extHostDocumentsAndEditors = new ExtHostDocumentsAndEditors(threadService);
// extHostDocumentsAndEditors.$acceptDocumentsAndEditorsDelta({
// addedDocuments: [{
// isDirty: false,
// versionId: model.getVersionId(),
// modeId: model.getLanguageIdentifier().language,
// url: model.uri,
// lines: model.getValue().split(model.getEOL()),
// EOL: model.getEOL(),
// }]
// });
// const extHostDocuments = new ExtHostDocuments(threadService, extHostDocumentsAndEditors);
// threadService.set(ExtHostContext.ExtHostDocuments, extHostDocuments);
const heapService = new ExtHostHeapService();
// const heapService = new ExtHostHeapService();
const commands = new ExtHostCommands(threadService, heapService);
threadService.set(ExtHostContext.ExtHostCommands, commands);
threadService.setTestInstance(MainContext.MainThreadCommands, instantiationService.createInstance(MainThreadCommands));
// const commands = new ExtHostCommands(threadService, heapService);
// threadService.set(ExtHostContext.ExtHostCommands, commands);
// threadService.setTestInstance(MainContext.MainThreadCommands, instantiationService.createInstance(MainThreadCommands));
const diagnostics = new ExtHostDiagnostics(threadService);
threadService.set(ExtHostContext.ExtHostDiagnostics, diagnostics);
// const diagnostics = new ExtHostDiagnostics(threadService);
// threadService.set(ExtHostContext.ExtHostDiagnostics, diagnostics);
extHost = new ExtHostDataProtocol(threadService);
threadService.set(SqlExtHostContext.ExtHostDataProtocol, extHost);
// extHost = new ExtHostDataProtocol(threadService);
// threadService.set(SqlExtHostContext.ExtHostDataProtocol, extHost);
});
suiteTeardown(() => {
setUnexpectedErrorHandler(originalErrorHandler);
model.dispose();
// setUnexpectedErrorHandler(originalErrorHandler);
// model.dispose();
});
teardown(function () {
while (disposables.length) {
disposables.pop().dispose();
}
return threadService.sync();
// while (disposables.length) {
// disposables.pop().dispose();
// }
// return threadService.sync();
});
// --- outline
test('DataProvider, language flavor changed', function () {
assert.equal(DocumentSymbolProviderRegistry.all(model).length, 0);
let expectedParams = <data.DidChangeLanguageFlavorParams> {
uri: 'myuri',
language: 'sql'
};
let actualParams: data.DidChangeLanguageFlavorParams = undefined;
extHost.onDidChangeLanguageFlavor((e => {
actualParams = e;
}));
extHost.$languageFlavorChanged(expectedParams);
assert.ok(actualParams !== undefined);
assert.equal(actualParams.uri, expectedParams.uri);
assert.equal(actualParams.flavor, expectedParams.flavor);
assert.equal(actualParams.language, expectedParams.language);
});
});