-
Notifications
You must be signed in to change notification settings - Fork 584
Expand file tree
/
Copy pathpublishProjectWebViewController.test.ts
More file actions
1726 lines (1439 loc) · 71 KB
/
publishProjectWebViewController.test.ts
File metadata and controls
1726 lines (1439 loc) · 71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from "vscode";
import * as mssql from "vscode-mssql";
import { expect } from "chai";
import * as chai from "chai";
import sinonChai from "sinon-chai";
import * as sinon from "sinon";
import VscodeWrapper from "../../src/controllers/vscodeWrapper";
import ConnectionManager from "../../src/controllers/connectionManager";
import MainController from "../../src/controllers/mainController";
import { ConnectionStore } from "../../src/models/connectionStore";
import { IConnectionProfileWithSource } from "../../src/models/interfaces";
import { PublishProjectWebViewController } from "../../src/publishProject/publishProjectWebViewController";
import { validateSqlServerPortNumber } from "../../src/publishProject/projectUtils";
import { validateSqlServerPassword } from "../../src/deployment/sqlServerContainer";
import { stubVscodeWrapper } from "./utils";
import {
PublishTarget,
PublishDialogState,
MaskMode,
PublishFormFields,
} from "../../src/sharedInterfaces/publishDialog";
import { ApiStatus } from "../../src/sharedInterfaces/webview";
import { SqlProjectsService } from "../../src/services/sqlProjectsService";
import { SqlPackageService } from "../../src/services/sqlPackageService";
import * as dockerUtils from "../../src/docker/dockerUtils";
import * as sqlServerContainer from "../../src/deployment/sqlServerContainer";
import * as projectUtils from "../../src/publishProject/projectUtils";
import { uuid } from "../e2e/baseFixtures";
import { ConnectionDetails } from "vscode-mssql";
import * as constants from "../../src/constants/constants";
import * as telemetry from "../../src/telemetry/telemetry";
import { TelemetryActions } from "../../src/sharedInterfaces/telemetry";
import { ServerType } from "../../src/models/connectionInfo";
chai.use(sinonChai);
suite("PublishProjectWebViewController Tests", () => {
let sandbox: sinon.SinonSandbox;
let contextStub: vscode.ExtensionContext;
let vscodeWrapperStub: sinon.SinonStubbedInstance<VscodeWrapper>;
let mockSqlProjectsService: sinon.SinonStubbedInstance<SqlProjectsService>;
let mockDacFxService: sinon.SinonStubbedInstance<mssql.IDacFxService>;
let mockSqlPackageService: sinon.SinonStubbedInstance<SqlPackageService>;
let mockConnectionManager: sinon.SinonStubbedInstance<ConnectionManager>;
let mockConnectionStore: sinon.SinonStubbedInstance<ConnectionStore>;
let mockMainController: sinon.SinonStubbedInstance<MainController>;
setup(() => {
sandbox = sinon.createSandbox();
const rawContext: Partial<vscode.ExtensionContext> = {
extensionUri: vscode.Uri.parse("file://ProjectPath"),
extensionPath: "ProjectPath",
subscriptions: [],
};
contextStub = rawContext as vscode.ExtensionContext;
vscodeWrapperStub = stubVscodeWrapper(sandbox);
// Create properly typed stubbed instances
mockSqlProjectsService = sandbox.createStubInstance(SqlProjectsService);
mockConnectionStore = sandbox.createStubInstance(ConnectionStore);
mockConnectionStore.readAllConnections.resolves([]);
// Create ConnectionManager mock manually (createStubInstance doesn't handle getters/event emitters well)
mockConnectionManager = {
listDatabases: sandbox.stub().resolves([]),
getConnectionString: sandbox.stub().resolves(""),
parseConnectionString: sandbox.stub().resolves({} as ConnectionDetails),
connect: sandbox.stub().resolves(true),
findMatchingProfile: sandbox.stub().resolves(undefined),
ensureAccountIdForAzureMfa: sandbox.stub().resolves(true),
getUriForConnection: sandbox.stub().returns(""),
isConnected: sandbox.stub().returns(false),
onSuccessfulConnection: sandbox.stub().returns({
dispose: sandbox.stub(),
} as vscode.Disposable),
onConnectionsChanged: sandbox.stub().returns({
dispose: sandbox.stub(),
} as vscode.Disposable),
connectionStore: mockConnectionStore,
activeConnections: {},
} as unknown as sinon.SinonStubbedInstance<ConnectionManager>;
// Create mock for interface (IDacFxService) - only stub methods we actually use in tests
mockDacFxService = {
getDeploymentOptions: sandbox.stub().resolves({ defaultDeploymentOptions: undefined }),
getOptionsFromProfile: sandbox.stub(),
savePublishProfile: sandbox.stub(),
deployDacpac: sandbox.stub(),
generateDeployScript: sandbox.stub(),
} as sinon.SinonStubbedInstance<mssql.IDacFxService>;
// Create mock for SqlPackageService
mockSqlPackageService = sandbox.createStubInstance(SqlPackageService);
// Create MainController mock - only stub methods we actually use in container creation
mockMainController = {
connectionManager: mockConnectionManager,
createObjectExplorerSession: sandbox.stub().resolves(),
} as unknown as sinon.SinonStubbedInstance<MainController>;
// Stub findAvailablePort — called eagerly in the constructor to pre-fetch the port.
sandbox.stub(dockerUtils, "findAvailablePort").resolves(1433);
});
teardown(() => {
sandbox.restore();
});
/**
* Helper factory to create PublishProjectWebViewController with default test setup.
* @param projectPath Optional project path (defaults to standard test path)
*/
function createTestController(
projectPath = "c:/work/TestProject.sqlproj",
): PublishProjectWebViewController {
return new PublishProjectWebViewController(
contextStub,
vscodeWrapperStub,
mockConnectionManager,
projectPath,
mockMainController,
mockSqlProjectsService,
mockDacFxService,
mockSqlPackageService,
);
}
/**
* Helper to get reducer handlers from controller, avoiding repeated casts.
*/
function getReducerHandlers(
controller: PublishProjectWebViewController,
): Map<string, Function> {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return (controller as any)._reducerHandlers;
}
test("constructor initializes state and derives database name", async () => {
const controller = createTestController("c:/work/MySampleProject.sqlproj");
await controller.initialized.promise;
// Verify initial state
expect(controller.state.projectFilePath).to.equal("c:/work/MySampleProject.sqlproj");
expect(controller.state.formState.databaseName).to.equal("MySampleProject");
// Form components should be initialized after initialization completes
const components = controller.state.formComponents;
expect(components.serverName, "serverName component should exist").to.exist;
expect(components.databaseName, "databaseName component should exist").to.exist;
expect(components.publishTarget, "publishTarget component should exist").to.exist;
});
test("reducer handlers are registered on construction", async () => {
const controller = createTestController();
await controller.initialized.promise;
// Access internal reducer handlers map
const reducerHandlers = getReducerHandlers(controller);
// Verify all expected reducers are registered
expect(reducerHandlers.has("publishNow"), "publishNow reducer should be registered").to.be
.true;
expect(
reducerHandlers.has("generatePublishScript"),
"generatePublishScript reducer should be registered",
).to.be.true;
expect(
reducerHandlers.has("selectPublishProfile"),
"selectPublishProfile reducer should be registered",
).to.be.true;
expect(
reducerHandlers.has("savePublishProfile"),
"savePublishProfile reducer should be registered",
).to.be.true;
expect(
reducerHandlers.has("updateDeploymentOptions"),
"updateDeploymentOptions reducer should be registered",
).to.be.true;
});
test("default publish target is EXISTING_SERVER", async () => {
const controller = createTestController();
await controller.initialized.promise;
expect(controller.state.formState.publishTarget).to.equal(PublishTarget.ExistingServer);
});
test("getActiveFormComponents returns correct fields for EXISTING_SERVER target", async () => {
const controller = createTestController();
await controller.initialized.promise;
// Set publish target to EXISTING_SERVER (default)
controller.state.formState.publishTarget = PublishTarget.ExistingServer;
const activeComponents = controller["getActiveFormComponents"](controller.state);
// Should include basic fields but NOT container fields
expect(activeComponents).to.include("publishTarget");
expect(activeComponents).to.include("publishProfilePath");
expect(activeComponents).to.include("serverName");
expect(activeComponents).to.include("databaseName");
// Should NOT include container fields
expect(activeComponents).to.not.include("containerPort");
expect(activeComponents).to.not.include("containerAdminPassword");
});
test("getActiveFormComponents returns correct fields for LOCAL_CONTAINER target", async () => {
const controller = createTestController();
await controller.initialized.promise;
// Set publish target to LOCAL_CONTAINER
controller.state.formState.publishTarget = PublishTarget.LocalContainer;
const activeComponents = controller["getActiveFormComponents"](controller.state);
// Should include basic fields AND container fields
expect(activeComponents).to.include("publishTarget");
expect(activeComponents).to.include("publishProfilePath");
expect(activeComponents).to.include("databaseName");
// Should include container fields
expect(activeComponents).to.include("containerPort");
expect(activeComponents).to.include("containerAdminPassword");
expect(activeComponents).to.include("containerAdminPasswordConfirm");
expect(activeComponents).to.include("containerImageTag");
expect(activeComponents).to.include("acceptContainerLicense");
});
test("formAction reducer saves values to formState and updates visibility", async () => {
const controller = createTestController("c:/work/ContainerProject.sqlproj");
await controller.initialized.promise;
const reducerHandlers = getReducerHandlers(controller);
const formAction = reducerHandlers.get("formAction");
expect(formAction, "formAction reducer should be registered").to.exist;
// Test setting a value updates formState
await formAction(controller.state, {
event: {
propertyName: "publishTarget",
value: PublishTarget.LocalContainer,
isAction: false,
},
});
expect(controller.state.formState.publishTarget).to.equal(PublishTarget.LocalContainer);
// Test that changing publish target updates field visibility
expect(
controller.state.formComponents.containerPort?.hidden,
"containerPort should be visible for LocalContainer target",
).to.not.be.true;
expect(
controller.state.formComponents.serverName?.hidden,
"serverName should be hidden for LocalContainer target",
).to.be.true;
});
test("Azure SQL project shows Azure-specific labels", async () => {
const mockSqlProjectsService: Partial<SqlProjectsService> = {
getProjectProperties: sinon.stub().resolves({
success: true,
databaseSchemaProvider:
"Microsoft.Data.Tools.Schema.Sql.SqlAzureV12DatabaseSchemaProvider",
outputPath: "bin/Debug",
}),
};
const controller = new PublishProjectWebViewController(
contextStub,
vscodeWrapperStub,
mockConnectionManager,
"test.sqlproj",
mockMainController,
mockSqlProjectsService as SqlProjectsService,
);
await controller.initialized.promise;
const publishTargetComponent = controller.state.formComponents.publishTarget;
const existingServerOption = publishTargetComponent.options?.find(
(opt) => opt.value === PublishTarget.ExistingServer,
);
const containerOption = publishTargetComponent.options?.find(
(opt) => opt.value === PublishTarget.LocalContainer,
);
expect(existingServerOption?.displayName).to.equal("Existing SQL Server");
expect(containerOption?.displayName).to.equal("New Local Docker SQL Server");
});
test("field validators enforce container and server requirements", () => {
// Port validation
expect(validateSqlServerPortNumber(1433)).to.be.true;
expect(validateSqlServerPortNumber(80)).to.be.true;
expect(validateSqlServerPortNumber(0), "port 0 invalid").to.be.false;
expect(validateSqlServerPortNumber(70000), "out-of-range port invalid").to.be.false;
expect(validateSqlServerPortNumber(1.5), "decimal port invalid").to.be.false;
expect(validateSqlServerPortNumber(-1), "negative port invalid").to.be.false;
// Password complexity validation (8-128 chars, 3 of 4: upper, lower, digit, special char)
// validateSqlServerPassword returns empty string for valid, error message for invalid
expect(validateSqlServerPassword("Abc123!@#"), "complex password valid").to.equal("");
expect(validateSqlServerPassword("MyTest99"), "3 categories valid").to.equal("");
expect(validateSqlServerPassword("alllower"), "simple lowercase invalid").to.not.equal("");
expect(validateSqlServerPassword("ALLUPPER"), "simple uppercase invalid").to.not.equal("");
expect(validateSqlServerPassword("Short1"), "too short invalid").to.not.equal("");
expect(validateSqlServerPassword("Abc123!@#".repeat(20)), "too long invalid").to.not.equal(
"",
);
});
test("getSqlServerContainerTagsForTargetVersion filters versions correctly for SQL Server 2022", async () => {
// Mock deployment versions that would be returned from getSqlServerContainerVersions()
const mockDeploymentVersions = [
{ displayName: "SQL Server 2025 image (latest)", value: "2025-latest" },
{ displayName: "SQL Server 2022 image", value: "2022" },
{ displayName: "SQL Server 2019 image", value: "2019" },
{ displayName: "SQL Server 2017 image", value: "2017" },
];
sandbox
.stub(sqlServerContainer, "getSqlServerContainerVersions")
.resolves(mockDeploymentVersions);
const result = await projectUtils.getSqlServerContainerTagsForTargetVersion("160");
// Should return only versions >= 2022 (2025 and 2022, filtered out 2019 and 2017)
expect(result).to.have.lengthOf(2);
expect(result[0].displayName).to.equal("SQL Server 2025 image (latest)");
expect(result[1].displayName).to.equal("SQL Server 2022 image");
});
//#region Publish Profile Section Tests
// Shared test data
const SAMPLE_PUBLISH_PROFILE_XML = `<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<IncludeCompositeObjects>True</IncludeCompositeObjects>
<TargetDatabaseName>MyDatabase</TargetDatabaseName>
<DeployScriptFileName>MyDatabase.sql</DeployScriptFileName>
<TargetConnectionString>Data Source=myserver.database.windows.net;Persist Security Info=False;User ID=admin;Pooling=False;MultipleActiveResultSets=False;</TargetConnectionString>
<AllowIncompatiblePlatform>True</AllowIncompatiblePlatform>
<IgnoreComments>True</IgnoreComments>
<ProfileVersionNumber>1</ProfileVersionNumber>
</PropertyGroup>
<ItemGroup>
<SqlCmdVariable Include="Var1">
<Value>Value1</Value>
</SqlCmdVariable>
<SqlCmdVariable Include="Var2">
<Value>Value2</Value>
</SqlCmdVariable>
</ItemGroup>
</Project>`;
test("selectPublishProfile reducer parses XML profile correctly", async () => {
// Set up initial project SQLCMD variables (these are the project defaults)
mockSqlProjectsService.getSqlCmdVariables.resolves({
success: true,
errorMessage: "",
sqlCmdVariables: [
{ varName: "Var1", value: "$(Var1)", defaultValue: "Value1" },
{ varName: "Var2", value: "$(Var2)", defaultValue: "Value2" },
],
});
const controller = createTestController();
await controller.initialized.promise;
const profilePath = "c:/profiles/TestProfile.publish.xml";
// Mock file system read
const fs = await import("fs");
sandbox.stub(fs.promises, "readFile").resolves(SAMPLE_PUBLISH_PROFILE_XML);
// Mock file picker
sandbox.stub(vscode.window, "showOpenDialog").resolves([vscode.Uri.file(profilePath)]);
// Mock DacFx service to return deployment options matching XML
mockDacFxService.getOptionsFromProfile.resolves({
success: true,
errorMessage: "",
deploymentOptions: {
excludeObjectTypes: {
value: ["Users", "Logins"],
description: "",
displayName: "",
},
booleanOptionsDictionary: {
allowIncompatiblePlatform: {
value: true,
description: "Allow incompatible platform",
displayName: "Allow Incompatible Platform",
},
ignoreComments: {
value: true,
description: "Ignore comments",
displayName: "Ignore Comments",
},
},
objectTypesDictionary: {},
},
});
const reducerHandlers = getReducerHandlers(controller);
const selectPublishProfile = reducerHandlers.get("selectPublishProfile");
expect(selectPublishProfile, "selectPublishProfile reducer should be registered").to.exist;
// Invoke the reducer
const newState = await selectPublishProfile(controller.state, {});
// Verify parsed values
expect(newState.formState.publishProfilePath.replace(/\\/g, "/")).to.equal(profilePath);
expect(newState.formState.databaseName).to.equal("MyDatabase");
expect(newState.formState.serverName).to.equal("myserver.database.windows.net");
// Verify SQLCMD variables from profile XML
expect(newState.formState.sqlCmdVariables).to.deep.equal({
Var1: "Value1",
Var2: "Value2",
});
// Verify original values are updated
expect(newState.defaultSqlCmdVariables).to.deep.equal({
Var1: "Value1",
Var2: "Value2",
});
// Verify deployment options were loaded from DacFx matching XML properties
expect(mockDacFxService.getOptionsFromProfile).to.have.been.calledOnce;
expect(newState.deploymentOptions.excludeObjectTypes.value).to.deep.equal([
"Users",
"Logins",
]);
expect(
newState.deploymentOptions.booleanOptionsDictionary.allowIncompatiblePlatform?.value,
"allowIncompatiblePlatform should be true from parsed profile",
).to.be.true;
expect(
newState.deploymentOptions.booleanOptionsDictionary.ignoreComments?.value,
"ignoreComments should be true from parsed profile",
).to.be.true;
});
test("savePublishProfile reducer is invoked and triggers save file dialog", async () => {
const controller = createTestController();
await controller.initialized.promise;
// Set up connection URI so getConnectionStringOnDemand works
controller["_connectionUri"] = "mssql://test-connection";
mockConnectionManager.getConnectionString.resolves(
"Server=myserver.database.windows.net;Database=ProductionDB",
);
// Set up server and database state
controller.state.formState.serverName = "myserver.database.windows.net";
controller.state.formState.databaseName = "ProductionDB";
controller.state.formState.sqlCmdVariables = {
EnvironmentName: "Production",
};
// Set up deployment options state
controller.state.deploymentOptions = {
excludeObjectTypes: {
value: ["Users", "Permissions"],
description: "Object types to exclude",
displayName: "Exclude Object Types",
},
booleanOptionsDictionary: {
ignoreTableOptions: {
value: true,
description: "Ignore table options",
displayName: "Ignore Table Options",
},
allowIncompatiblePlatform: {
value: false,
description: "Allow incompatible platform",
displayName: "Allow Incompatible Platform",
},
},
objectTypesDictionary: {
users: "Users",
permissions: "Permissions",
},
};
// Stub showSaveDialog to simulate user choosing a save location
const savedProfilePath = "c:/profiles/ProductionProfile.publish.xml";
sandbox.stub(vscode.window, "showSaveDialog").resolves(vscode.Uri.file(savedProfilePath));
// Mock DacFx service
mockDacFxService.savePublishProfile.resolves({ success: true, errorMessage: "" });
const reducerHandlers = getReducerHandlers(controller);
const savePublishProfile = reducerHandlers.get("savePublishProfile");
expect(savePublishProfile, "savePublishProfile reducer should be registered").to.exist;
// Invoke the reducer
await savePublishProfile(controller.state, {
publishProfileName: "ProductionProfile.publish.xml",
});
// Verify DacFx save was called with correct parameters
expect(mockDacFxService.savePublishProfile).to.have.been.calledOnce;
const saveCall = mockDacFxService.savePublishProfile.getCall(0);
expect(saveCall.args[0].replace(/\\/g, "/")).to.equal(savedProfilePath); // File path (normalize for cross-platform)
expect(saveCall.args[1]).to.equal("ProductionDB"); // Database name
// Connection string is args[2]
const sqlCmdVariables = saveCall.args[3]; // SQL CMD variables
expect(sqlCmdVariables.get("EnvironmentName")).to.equal("Production");
// Verify deployment options are included (args[4])
const deploymentOptions = saveCall.args[4];
expect(deploymentOptions).to.exist;
expect(deploymentOptions.excludeObjectTypes.value).to.deep.equal(["Users", "Permissions"]);
expect(
deploymentOptions.booleanOptionsDictionary.ignoreTableOptions?.value,
"ignoreTableOptions should be true in saved deployment options",
).to.be.true;
expect(
deploymentOptions.booleanOptionsDictionary.allowIncompatiblePlatform?.value,
"allowIncompatiblePlatform should be false in saved deployment options",
).to.be.false;
});
test("connectAndPopulateDatabases with Azure MFA connection without accountId - populates accountId from saved profile", async () => {
const controller = createTestController();
await controller.initialized.promise;
// Mock connection string with Azure MFA authentication but without accountId
const azureMfaConnectionString =
"Server=azure-server.database.windows.net;Database=testdb;Authentication=Active Directory Interactive;User [email protected];";
// Mock parseConnectionString to return connection details without accountId
const mockConnectionDetails: Partial<ConnectionDetails> = {
options: {
server: "azure-server.database.windows.net",
database: "testdb",
authenticationType: "AzureMFA",
user: "[email protected]",
email: "[email protected]",
accountId: undefined, // Missing accountId - this is what we're testing
},
};
mockConnectionManager.parseConnectionString.resolves(
mockConnectionDetails as ConnectionDetails,
);
// Configure the ensureAccountIdForAzureMfa stub to populate accountId
mockConnectionManager.ensureAccountIdForAzureMfa.callsFake(async (connInfo) => {
// Simulate what the real method does - populate accountId from saved profile
connInfo.accountId = "test-account-id-67890";
return true;
});
// Configure connect stub to succeed
mockConnectionManager.connect.resolves(true);
// Configure listDatabases stub to return sample databases
mockConnectionManager.listDatabases.resolves(["testdb", "master", "model"]);
// Call the private method with state as first argument
const result = await controller["connectAndPopulateDatabases"](
controller.state,
azureMfaConnectionString,
);
// Verify the helper was called to populate missing accountId
expect(mockConnectionManager.ensureAccountIdForAzureMfa).to.have.been.calledOnce;
// Verify accountId was populated by checking the argument passed to connect
const connectCallArgs = mockConnectionManager.connect.firstCall.args;
const connectionInfoPassedToConnect = connectCallArgs[1];
expect(connectionInfoPassedToConnect.accountId).to.equal("test-account-id-67890");
// Verify connect was called (which means accountId was populated successfully)
expect(mockConnectionManager.connect).to.have.been.calledOnce;
// Verify connection succeeded (returns connection URI string, not undefined)
expect(result).to.exist;
expect(result).to.be.a("string");
// Verify databases were populated in the component
const databaseComponent = controller.state.formComponents.databaseName;
expect(databaseComponent.options).to.have.lengthOf(3);
expect(databaseComponent.options![0].value).to.equal("testdb");
});
//#endregion
//#region Server and Database Connection Section Tests
test("server and database fields are initialized with correct default values", async () => {
const controller = createTestController("c:/work/MyTestProject.sqlproj");
await controller.initialized.promise;
// Verify server component and default value
const serverComponent = controller.state.formComponents.serverName;
expect(serverComponent).to.exist;
expect(serverComponent.label).to.exist;
expect(serverComponent.required, "serverName component should be required").to.be.true;
expect(controller.state.formState.serverName).to.equal("");
// Verify database component and default value (project name)
const databaseComponent = controller.state.formComponents.databaseName;
expect(databaseComponent).to.exist;
expect(databaseComponent.label).to.exist;
expect(databaseComponent.required, "databaseName component should be required").to.be.true;
expect(controller.state.formState.databaseName).to.equal("MyTestProject");
});
test("formAction updates server and database names via user interaction", async () => {
const controller = createTestController();
await controller.initialized.promise;
const reducerHandlers = getReducerHandlers(controller);
const formAction = reducerHandlers.get("formAction");
expect(formAction, "formAction reducer should be registered").to.exist;
// Simulate connection dialog setting server name
await formAction(controller.state, {
event: {
propertyName: "serverName",
value: "localhost,1433",
isAction: false,
},
});
// Verify server name is updated
expect(controller.state.formState.serverName).to.equal("localhost,1433");
// Simulate user selecting a database from dropdown
await formAction(controller.state, {
event: {
propertyName: "databaseName",
value: "SelectedDatabase",
isAction: false,
},
});
// Verify database name is updated
expect(controller.state.formState.databaseName).to.equal("SelectedDatabase");
});
test("connectToServer reducer loads saved connections and populates database list on connect", async () => {
// Setup mock saved connections
const mockSavedConnections: Partial<IConnectionProfileWithSource>[] = [
{
id: "profile-1",
server: "testserver.database.windows.net",
database: "master",
user: "testuser",
profileName: "Test Server",
authenticationType: "SqlLogin",
},
];
const mockDatabases = ["master", "tempdb", "MyDatabase"];
mockConnectionStore.readAllConnections.resolves(
mockSavedConnections as IConnectionProfileWithSource[],
);
mockConnectionManager.connect.resolves(true);
mockConnectionManager.getUriForConnection.returns("mssql://testserver");
mockConnectionManager.isConnected.returns(false);
mockConnectionManager.listDatabases.resolves(mockDatabases);
mockConnectionManager.getConnectionString.resolves("Server=testserver;Database=master");
const controller = createTestController();
await controller.initialized.promise;
// Verify server dropdown is populated from saved connections
const serverComponent = controller.state.formComponents.serverName;
expect(serverComponent.options).to.have.length(1);
expect(serverComponent.options[0].displayName).to.equal("Test Server");
// Get and call the connectToServer reducer
const reducerHandlers = getReducerHandlers(controller);
const connectToServer = reducerHandlers.get("connectToServer");
expect(connectToServer, "connectToServer reducer should be registered").to.exist;
await connectToServer(controller.state, { connectionId: "profile-1" });
// Verify database dropdown is populated after connection
const databaseComponent = controller.state.formComponents.databaseName;
expect(databaseComponent.options).to.have.length(3);
expect(databaseComponent.options.map((o: { value: string }) => o.value)).to.include(
"MyDatabase",
);
// Verify state is updated correctly
expect(controller.state.selectedProfileId).to.equal("profile-1");
expect(controller.state.loadConnectionStatus).to.equal(ApiStatus.Loaded);
});
test("connectToServer reducer handles connection failure and displays error", async () => {
const mockSavedConnections: Partial<IConnectionProfileWithSource>[] = [
{
id: "profile-1",
server: "badserver.database.windows.net",
database: "master",
user: "testuser",
profileName: "Bad Server",
authenticationType: "SqlLogin",
},
];
mockConnectionStore.readAllConnections.resolves(
mockSavedConnections as IConnectionProfileWithSource[],
);
mockConnectionManager.connect.resolves(false);
mockConnectionManager.getUriForConnection.returns("");
mockConnectionManager.isConnected.returns(false);
const controller = createTestController();
await controller.initialized.promise;
const reducerHandlers = getReducerHandlers(controller);
const connectToServer = reducerHandlers.get("connectToServer");
await connectToServer(controller.state, { connectionId: "profile-1" });
// Verify error message is displayed
expect(controller.state.formMessage).to.exist;
expect(controller.state.formMessage?.intent).to.equal("error");
// Verify database dropdown is cleared on error
const databaseComponent = controller.state.formComponents.databaseName;
expect(databaseComponent.options).to.have.length(0);
// Verify loading status is properly set to error
expect(controller.state.loadConnectionStatus).to.equal(ApiStatus.Error);
});
//#endregion
//#region Advanced Options Section Tests
test("deployment options should have three groups: General, Ignore, and Exclude", async () => {
const controller = createTestController();
await controller.initialized.promise;
// Set up comprehensive deployment options with all three types
const deploymentOptions = {
excludeObjectTypes: {
value: [],
description: "Object types to exclude",
displayName: "Exclude Object Types",
},
booleanOptionsDictionary: {
allowDropBlockingAssemblies: {
value: false,
description: "Allow drop blocking assemblies",
displayName: "Allow Drop Blocking Assemblies",
},
ignoreTableOptions: {
value: false,
description: "Ignore table options during deployment",
displayName: "Ignore Table Options",
},
ignoreIndexes: {
value: false,
description: "Ignore indexes during deployment",
displayName: "Ignore Indexes",
},
},
objectTypesDictionary: {
users: "Users",
logins: "Logins",
tables: "Tables",
},
};
const reducerHandlers = getReducerHandlers(controller);
const updateDeploymentOptions = reducerHandlers.get("updateDeploymentOptions");
// Update deployment options
const newState = await updateDeploymentOptions(controller.state, {
deploymentOptions,
});
// Verify we have the expected structure
expect(newState.deploymentOptions.booleanOptionsDictionary).to.exist;
expect(newState.deploymentOptions.objectTypesDictionary).to.exist;
expect(newState.deploymentOptions.excludeObjectTypes).to.exist;
// Verify General group - one option that doesn't start with "Ignore"
expect(newState.deploymentOptions.booleanOptionsDictionary.allowDropBlockingAssemblies).to
.exist;
// Verify Ignore group - one option that starts with "Ignore"
expect(newState.deploymentOptions.booleanOptionsDictionary.ignoreTableOptions).to.exist;
// Verify Exclude group - object types dictionary
expect(newState.deploymentOptions.objectTypesDictionary.users).to.equal("Users");
});
test("updateDeploymentOptions reducer should save and collect options properly", async () => {
const controller = createTestController();
await controller.initialized.promise;
const originalOptions = {
excludeObjectTypes: {
value: ["Users"],
description: "Object types to exclude",
displayName: "Exclude Object Types",
},
booleanOptionsDictionary: {
allowDropBlockingAssemblies: {
value: false,
description: "Allow drop blocking assemblies",
displayName: "Allow Drop Blocking Assemblies",
},
},
objectTypesDictionary: {
users: "Users",
logins: "Logins",
},
};
const updatedOptions = {
excludeObjectTypes: {
value: ["Users", "Logins"],
description: "Object types to exclude",
displayName: "Exclude Object Types",
},
booleanOptionsDictionary: {
allowDropBlockingAssemblies: {
value: true,
description: "Allow drop blocking assemblies",
displayName: "Allow Drop Blocking Assemblies",
},
},
objectTypesDictionary: {
users: "Users",
logins: "Logins",
},
};
const reducerHandlers = getReducerHandlers(controller);
const updateDeploymentOptions = reducerHandlers.get("updateDeploymentOptions");
// Set initial state
let newState = await updateDeploymentOptions(controller.state, {
deploymentOptions: originalOptions,
});
// Verify initial state is saved correctly
expect(newState.deploymentOptions.excludeObjectTypes.value).to.deep.equal(["Users"]);
expect(
newState.deploymentOptions.booleanOptionsDictionary.allowDropBlockingAssemblies.value,
).to.be.false;
// Update with new options
newState = await updateDeploymentOptions(newState, {
deploymentOptions: updatedOptions,
});
// Verify updated state is collected properly
expect(newState.deploymentOptions.excludeObjectTypes.value).to.deep.equal([
"Users",
"Logins",
]);
expect(
newState.deploymentOptions.booleanOptionsDictionary.allowDropBlockingAssemblies.value,
).to.be.true;
});
test("deployment options reset restores default values", async () => {
const controller = createTestController();
await controller.initialized.promise;
const reducerHandlers = getReducerHandlers(controller);
const updateDeploymentOptions = reducerHandlers.get("updateDeploymentOptions");
// Set up default deployment options
const defaultOptions = {
excludeObjectTypes: { value: [], description: "", displayName: "" },
booleanOptionsDictionary: {
ignoreTableOptions: {
value: false,
description: "Ignore table options",
displayName: "Ignore Table Options",
},
},
objectTypesDictionary: {},
};
controller.state.defaultDeploymentOptions = defaultOptions;
// User makes changes
const modifiedOptions = structuredClone(defaultOptions);
modifiedOptions.booleanOptionsDictionary.ignoreTableOptions.value = true;
let state = await updateDeploymentOptions(controller.state, {
deploymentOptions: modifiedOptions,
});
// Verify change is applied
expect(state.deploymentOptions.booleanOptionsDictionary.ignoreTableOptions.value).to.be
.true;
// Reset should restore defaults
state = await updateDeploymentOptions(state, {
deploymentOptions: state.defaultDeploymentOptions,
});
// Verify reset to default value
expect(state.deploymentOptions.booleanOptionsDictionary.ignoreTableOptions.value).to.be
.false;
});
//#endregion
//#region Generate Script Tests
test("generatePublishScript reducer closes dialog and triggers script generation", async () => {
const controller = createTestController();
await controller.initialized.promise;
// Set up state with all required fields for script generation
controller.state.formState.serverName = "localhost";
controller.state.formState.databaseName = "TestDatabase";
controller["_connectionUri"] = "mssql://test-connection-uri";
controller.state.projectFilePath = "c:/work/TestProject.sqlproj";
// Mock the panel dispose method using sandbox stub
const panelDisposeSpy = sandbox.stub();
Object.defineProperty(controller, "panel", {
value: { dispose: panelDisposeSpy },
writable: true,
configurable: true,
});
// Spy on executePublishAndGenerateScript to verify it's called
const executePublishSpy = sandbox.stub(
controller as typeof controller & {
executePublishAndGenerateScript: (state: unknown, isPublish: boolean) => void;
},
"executePublishAndGenerateScript",
);
const reducerHandlers = getReducerHandlers(controller);
const generatePublishScript = reducerHandlers.get("generatePublishScript");
expect(generatePublishScript, "generatePublishScript reducer should be registered").to
.exist;
// Invoke the reducer
await generatePublishScript(controller.state, {});
// Verify dialog was closed
expect(panelDisposeSpy).to.have.been.calledOnce;
// Verify executePublishAndGenerateScript was called with isPublish=false
expect(executePublishSpy).to.have.been.calledOnce;
expect(
executePublishSpy.firstCall.args[1],
"isPublish parameter should be false for script generation",
).to.be.false;
});
//#endregion
//#region Publish Tests
test("publishNow reducer closes dialog and triggers publish", async () => {
const controller = createTestController();
await controller.initialized.promise;
// Set up state with all required fields for publish
controller.state.formState.serverName = "localhost";
controller.state.formState.databaseName = "TestDatabase";
controller["_connectionUri"] = "mssql://test-connection-uri";
controller.state.projectFilePath = "c:/work/TestProject.sqlproj";
// Mock the panel dispose method using sandbox stub
const panelDisposeSpy = sandbox.stub();
Object.defineProperty(controller, "panel", {
value: { dispose: panelDisposeSpy },
writable: true,
configurable: true,
});
// Spy on executePublishAndGenerateScript to verify it's called
const executePublishSpy = sandbox.stub(
controller as typeof controller & {
executePublishAndGenerateScript: (state: unknown, isPublish: boolean) => void;