This repository was archived by the owner on Jan 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathIQsharpEngineTests.cs
More file actions
974 lines (815 loc) · 38 KB
/
Copy pathIQsharpEngineTests.cs
File metadata and controls
974 lines (815 loc) · 38 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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Data;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Collections.Immutable;
using Microsoft.Jupyter.Core;
using Microsoft.Jupyter.Core.Protocol;
using Microsoft.Quantum.IQSharp;
using Microsoft.Quantum.IQSharp.Jupyter;
using Microsoft.Quantum.IQSharp.Kernel;
using Microsoft.Quantum.IQSharp.ExecutionPathTracer;
using Microsoft.Quantum.Simulation.OpenSystems.DataModel;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;
using Microsoft.Extensions.DependencyInjection;
using LlvmBindings.Values;
using YamlDotNet.Core;
#pragma warning disable VSTHRD200 // Use "Async" suffix for async methods
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
namespace Tests.IQSharp
{
[TestClass]
public class IQSharpEngineTests
{
public async static Task<IQSharpEngine> Init(string workspace = "Workspace", Action<IServiceProvider>? configure = null)
{
System.Environment.SetEnvironmentVariable("RUST_BACKTRACE", "1");
var engine = Startup.Create<IQSharpEngine>(workspace, configure);
engine.Start();
await engine.Initialized;
Assert.IsNotNull(engine.Workspace);
await engine.Workspace!.Initialization;
return engine;
}
public async static Task<IQSharpEngine> Init(string workspace, Func<IServiceProvider, Task> configure)
{
System.Environment.SetEnvironmentVariable("RUST_BACKTRACE", "1");
var engine = await Startup.Create<IQSharpEngine>(workspace, configure);
engine.Start();
await engine.Initialized;
Assert.IsNotNull(engine.Workspace);
await engine.Workspace!.Initialization;
return engine;
}
public static void PrintResult(ExecutionResult result, MockChannel channel)
{
Console.WriteLine("Result:");
Console.WriteLine(JsonConvert.SerializeObject(result));
Console.WriteLine("Errors:");
foreach (var m in channel.errors) Console.WriteLine($" {m}");
Console.WriteLine("Messages:");
foreach (var m in channel.msgs) Console.WriteLine($" {m}");
}
public static string SessionAsString(IEnumerable<Message> session) =>
string.Join("\n",
session.Select(message =>
$"\tHeader: {JsonConvert.SerializeObject(message.Header)}\n" +
$"\tParent header: {JsonConvert.SerializeObject(message.ParentHeader)}\n" +
$"\tMetadata: {JsonConvert.SerializeObject(message.Metadata)}\n" +
$"\tContent: {JsonConvert.SerializeObject(message.Content)}\n\n"
)
);
public static async Task<string?> AssertCompile(IQSharpEngine engine, string source, params string[] expectedOps)
{
var channel = new MockChannel();
var response = await engine.ExecuteMundane(source, channel);
PrintResult(response, channel);
Assert.AreEqual(ExecuteStatus.Ok, response.Status);
CollectionAssert.AreEquivalent(expectedOps, response.Output as string[]);
return response.Output?.ToString();
}
public static async Task<string?> AssertSimulate(IQSharpEngine engine, string snippetName, params string[] messages)
{
await engine.Initialized;
var configSource = new ConfigurationSource(skipLoading: true, eventService: null);
var simMagic = new SimulateMagic(engine.SymbolsResolver!, configSource,
new PerformanceMonitor(),
new UnitTestLogger<SimulateMagic>());
var channel = new MockChannel();
var response = await simMagic.Execute(snippetName, channel);
PrintResult(response, channel);
Assert.AreEqual(ExecuteStatus.Ok, response.Status);
CollectionAssert.AreEqual(messages.Select(ChannelWithNewLines.Format).ToArray(), channel.msgs.ToArray());
return response.Output?.ToString();
}
public static async Task<string?> AssertNoisySimulate(IQSharpEngine engine, string snippetName, string? representation, NoiseModel? noiseModel, params string[] messages)
{
await engine.Initialized;
var configSource = new ConfigurationSource(skipLoading: true);
var noiseModelSource = new NoiseModelSource();
if (noiseModel is not null)
{
noiseModelSource.NoiseModel = noiseModel;
}
if (representation is not null)
{
configSource.Configuration["simulators.noisy.representation"] = representation;
}
var simMagic = new SimulateNoiseMagic(
engine,
resolver: engine.SymbolsResolver!,
configurationSource: configSource,
logger: new UnitTestLogger<SimulateNoiseMagic>(),
noiseModelSource: noiseModelSource
);
var channel = new MockChannel();
var response = await simMagic.Execute(snippetName, channel);
PrintResult(response, channel);
response.AssertIsOk();
CollectionAssert.AreEqual(messages.Select(ChannelWithNewLines.Format).ToArray(), channel.msgs.ToArray());
return response.Output?.ToString();
}
private async Task AssertTrace(string name, ExecutionPath expectedPath, int expectedDepth)
{
var engine = await Init("Workspace.ExecutionPathTracer");
var snippets = engine.Snippets as Snippets;
Assert.IsNotNull(snippets);
Assert.IsNotNull(engine.SymbolsResolver);
var configSource = new ConfigurationSource(skipLoading: true);
var wsMagic = new WorkspaceMagic(snippets!.Workspace, new UnitTestLogger<WorkspaceMagic>());
var pkgMagic = new PackageMagic(snippets.GlobalReferences, new UnitTestLogger<PackageMagic>());
var traceMagic = new TraceMagic(engine.SymbolsResolver!, configSource, new UnitTestLogger<TraceMagic>());
var channel = new MockChannel();
// Add dependencies:
var response = await pkgMagic.Execute("mock.standard", channel);
PrintResult(response, channel);
response.AssertIsOk();
// Reload workspace:
response = await wsMagic.Execute("reload", channel);
PrintResult(response, channel);
response.AssertIsOk();
response = await traceMagic.Execute(name, channel);
PrintResult(response, channel);
response.AssertIsOk();
var message = channel.iopubMessages.ElementAtOrDefault(0);
Assert.IsNotNull(message);
Assert.AreEqual("render_execution_path", message.Header.MessageType);
var content = message.Content as ExecutionPathVisualizerContent;
Assert.IsNotNull(content);
Assert.AreEqual(expectedDepth, content?.RenderDepth);
var path = content?.ExecutionPath.ToObject<ExecutionPath>();
Assert.IsNotNull(path);
Assert.AreEqual(expectedPath.ToJson(), path!.ToJson());
}
[TestMethod]
public async Task CompleteMagic() =>
await Assert.That
.UsingEngine()
.Input("%sim", 3)
.CompletesTo(
"%simulate",
"%simulate_noise",
"%simulate_sparse"
)
.Input("%ls", 3)
.CompletesTo(
"%lsopen",
"%lsmagic"
);
[TestMethod]
public async Task CompileOne()
{
var engine = await Init();
await AssertCompile(engine, SNIPPETS.HelloQ, "HelloQ");
}
[TestMethod]
public async Task CompileAndSimulate()
{
var engine = await Init();
Assert.IsNotNull(engine.SymbolsResolver);
var configSource = new ConfigurationSource(skipLoading: true);
var simMagic = new SimulateMagic(engine.SymbolsResolver!, configSource, new PerformanceMonitor(), new UnitTestLogger<SimulateMagic>());
var channel = new MockChannel();
// Try running without compiling it, fails:
var response = await simMagic.Execute("_snippet_.HelloQ", channel);
PrintResult(response, channel);
Assert.AreEqual(ExecuteStatus.Error, response.Status);
Assert.AreEqual(0, channel.msgs.Count);
Assert.AreEqual(1, channel.errors.Count);
Assert.AreEqual(
ChannelWithNewLines.Format(
"No Q# operation with name `_snippet_.HelloQ` has been defined.\n" +
"Hint: You may have misspelled the name `_snippet_.HelloQ`, or you may have forgotten to run a cell above."
),
channel.errors[0]
);
// Compile it:
await AssertCompile(engine, SNIPPETS.HelloQ, "HelloQ");
// Try running again:
await AssertSimulate(engine, "HelloQ", "Hello from quantum world!");
}
[TestMethod]
public async Task SimulateWithArguments()
{
var engine = await Init();
// Compile it:
await AssertCompile(engine, SNIPPETS.Reverse, "Reverse");
// Try running again:
var results = await AssertSimulate(engine, "Reverse { \"array\": [2, 3, 4], \"name\": \"foo\" }", "Hello foo");
Assert.AreEqual("[4,3,2]", results);
}
[TestMethod]
public async Task OpenNamespaces()
{
var engine = await Init();
// Compile:
await AssertCompile(engine, SNIPPETS.OpenNamespaces1);
await AssertCompile(engine, SNIPPETS.OpenNamespaces2);
await AssertCompile(engine, SNIPPETS.DependsOnNamespace, "DependsOnNamespace");
// Run:
await AssertSimulate(engine, "DependsOnNamespace", "Hello from DependsOnNamespace", "Hello from quantum world!");
}
[TestMethod]
public async Task OpenAliasedNamespaces()
{
var engine = await Init();
// Compile:
await AssertCompile(engine, SNIPPETS.OpenAliasedNamespace);
await AssertCompile(engine, SNIPPETS.DependsOnAliasedNamespace, "DependsOnAliasedNamespace");
// Run:
await AssertSimulate(engine, "DependsOnAliasedNamespace", "Hello from DependsOnAliasedNamespace");
}
[TestMethod]
public async Task CompileApplyWithin()
{
var engine = await Init();
// Compile:
await AssertCompile(engine, SNIPPETS.ApplyWithinBlock, "ApplyWithinBlock");
// Run:
await AssertSimulate(engine, "ApplyWithinBlock", "Within", "Apply", "Within");
}
[TestMethod]
public async Task NoisySimulateWithTwoQubitOperation()
{
var engine = await Init();
var channel = new MockChannel();
// Compile it:
await AssertCompile(engine, SNIPPETS.SimpleDebugOperation, "SimpleDebugOperation");
// Try running again:
// Note that noiseModel: null sets the noise model to be ideal.
await AssertNoisySimulate(engine, "SimpleDebugOperation", representation: "mixed", noiseModel: null);
}
[TestMethod]
public async Task NoisySimulateWithFailIfOne()
{
var engine = await Init();
var channel = new MockChannel();
// Compile it:
await AssertCompile(engine, SNIPPETS.FailIfOne, "FailIfOne");
// Try running again:
// Note that noiseModel: null sets the noise model to be ideal.
await AssertNoisySimulate(engine, "FailIfOne", representation: "mixed", noiseModel: null);
}
[TestMethod]
public async Task NoisySimulateWithTrivialOperation()
{
var engine = await Init();
var channel = new MockChannel();
// Compile it:
await AssertCompile(engine, SNIPPETS.HelloQ, "HelloQ");
// Try running again:
await AssertNoisySimulate(engine, "HelloQ", representation: "mixed", noiseModel: null, "Hello from quantum world!");
}
[TestMethod]
public async Task Toffoli()
{
var engine = await Init();
var channel = new MockChannel();
Assert.IsNotNull(engine.SymbolsResolver);
// Compile it:
await AssertCompile(engine, SNIPPETS.HelloQ, "HelloQ");
// Run with toffoli simulator:
var toffoliMagic = new ToffoliMagic(engine.SymbolsResolver!, new UnitTestLogger<ToffoliMagic>());
var response = await toffoliMagic.Execute("HelloQ", channel);
var result = response.Output as Dictionary<string, double>;
PrintResult(response, channel);
response.AssertIsOk();
Assert.AreEqual(1, channel.msgs.Count);
Assert.AreEqual(ChannelWithNewLines.Format("Hello from quantum world!"), channel.msgs[0]);
}
[TestMethod]
public async Task DependsOnWorkspace()
{
var engine = await Init();
// Compile it:
await AssertCompile(engine, SNIPPETS.DependsOnWorkspace, "DependsOnWorkspace");
// Run:
var results = await AssertSimulate(engine, "DependsOnWorkspace", "Hello Foo again!");
Assert.AreEqual("[Zero,One,Zero,Zero,Zero]", results);
}
[TestMethod]
public async Task UpdateSnippet()
{
var engine = await Init();
// Compile it:
await AssertCompile(engine, SNIPPETS.HelloQ, "HelloQ");
// Run:
await AssertSimulate(engine, "HelloQ", "Hello from quantum world!");
// Compile it with a new code
await AssertCompile(engine, SNIPPETS.HelloQ_2, "HelloQ");
// Run again:
await AssertSimulate(engine, "HelloQ", "msg0", "msg1");
}
[TestMethod]
public async Task DumpToFile()
{
var engine = await Init();
// Compile DumpMachine snippet.
await AssertCompile(engine, SNIPPETS.DumpToFile, "DumpToFile");
// Run, which should produce files in working directory.
await AssertSimulate(engine, "DumpToFile", "Dumped to file!");
// Ensure the expected files got created.
var machineFile = "DumpMachine.txt";
var registerFile = "DumpRegister.txt";
Assert.IsTrue(System.IO.File.Exists(machineFile));
Assert.IsTrue(System.IO.File.Exists(registerFile));
// Clean up produced files, if any.
if (System.IO.File.Exists(machineFile))
{
System.IO.File.Delete(machineFile);
}
if (System.IO.File.Exists(registerFile))
{
System.IO.File.Delete(registerFile);
}
}
[TestMethod]
public async Task UpdateDependency()
{
var engine = await Init();
// Compile HelloQ
await AssertCompile(engine, SNIPPETS.HelloQ, "HelloQ");
// Compile something that depends on it:
await AssertCompile(engine, SNIPPETS.DependsOnHelloQ, "DependsOnHelloQ");
// Compile new version of HelloQ
await AssertCompile(engine, SNIPPETS.HelloQ_2, "HelloQ");
// Run dependency, it should reflect changes on HelloQ:
await AssertSimulate(engine, "DependsOnHelloQ", "msg0", "msg1");
}
[TestMethod]
public async Task ReportWarnings()
{
var engine = await Init();
{
var channel = new MockChannel();
await engine.Execute("%config errors.style = \"basic\"", channel, default);
channel = new MockChannel();
var response = await engine.ExecuteMundane(SNIPPETS.ThreeWarnings, channel);
PrintResult(response, channel);
response.AssertIsOk();
Assert.AreEqual(3, channel.msgs.Count);
Assert.AreEqual(0, channel.errors.Count);
Assert.AreEqual("ThreeWarnings",
new ListToTextResultEncoder().Encode(response.Output)?.Data
);
}
{
var channel = new MockChannel();
var response = await engine.ExecuteMundane(SNIPPETS.OneWarning, channel);
PrintResult(response, channel);
response.AssertIsOk();
Assert.AreEqual(1, channel.msgs.Count);
Assert.AreEqual(0, channel.errors.Count);
Assert.AreEqual("OneWarning",
new ListToTextResultEncoder().Encode(response.Output)?.Data
);
}
}
[TestMethod]
public async Task ReportErrors()
{
var engine = await Init();
var channel = new MockChannel();
await engine.Execute("%config errors.style = \"basic\"", channel, default);
channel = new MockChannel();
var response = await engine.ExecuteMundane(SNIPPETS.TwoErrors, channel);
PrintResult(response, channel);
Assert.AreEqual(ExecuteStatus.Error, response.Status);
Assert.AreEqual(0, channel.msgs.Count);
Assert.AreEqual(2, channel.errors.Count);
}
[TestMethod]
public async Task TestPackages()
{
var engine = await Init();
var snippets = engine.Snippets as Snippets;
Assert.IsNotNull(snippets);
var pkgMagic = new PackageMagic(snippets!.GlobalReferences, new UnitTestLogger<PackageMagic>());
var references = ((References)pkgMagic.References);
var packageCount = references.AutoLoadPackages.Count;
var channel = new MockChannel();
var response = await pkgMagic.Execute("", channel);
var result = response.Output as string[];
PrintResult(response, channel);
response.AssertIsOk();
Assert.AreEqual(0, channel.msgs.Count);
Assert.AreEqual(packageCount, result?.Length);
Assert.AreEqual("Microsoft.Quantum.Standard::0.0.0", result?[0]);
Assert.AreEqual("Microsoft.Quantum.Standard.Visualization::0.0.0", result?[1]);
// Try compiling TrotterEstimateEnergy, it should fail due to the lack
// of chemistry package.
response = await engine.ExecuteMundane(SNIPPETS.UseJordanWignerEncodingData, channel);
PrintResult(response, channel);
Assert.AreEqual(ExecuteStatus.Error, response.Status);
response = await pkgMagic.Execute("mock.chemistry", channel);
result = response.Output as string[];
PrintResult(response, channel);
response.AssertIsOk();
Assert.AreEqual(0, channel.msgs.Count);
Assert.IsNotNull(result);
Assert.AreEqual(packageCount + 1, result?.Length);
// Now it should compile:
await AssertCompile(engine, SNIPPETS.UseJordanWignerEncodingData, "UseJordanWignerEncodingData");
}
[TestMethod]
public async Task TestInvalidPackages()
{
var engine = await Init();
var snippets = engine.Snippets as Snippets;
Assert.IsNotNull(snippets);
var pkgMagic = new PackageMagic(snippets!.GlobalReferences, new UnitTestLogger<PackageMagic>());
var channel = new MockChannel();
var response = await pkgMagic.Execute("microsoft.invalid.quantum", channel);
var result = response.Output as string[];
PrintResult(response, channel);
Assert.AreEqual(ExecuteStatus.Error, response.Status);
Assert.AreEqual(1, channel.errors.Count);
Assert.IsTrue(channel.errors[0].StartsWith("Unable to find package 'microsoft.invalid.quantum'"));
Assert.IsNull(result);
}
[TestMethod]
public async Task TestProjectMagic()
{
var engine = await Init();
var snippets = engine.Snippets as Snippets;
Assert.IsNotNull(snippets);
var projectMagic = new ProjectMagic(snippets!.Workspace, new UnitTestLogger<ProjectMagic>());
var channel = new MockChannel();
var response = await projectMagic.Execute("../Workspace.ProjectReferences/Workspace.ProjectReferences.csproj", channel);
response.AssertIsOk();
var loadedProjectFiles = response.Output as string[];
Assert.AreEqual(3, loadedProjectFiles?.Length);
}
[TestMethod]
public async Task TestWho()
{
var snippets = Startup.Create<Snippets>("Workspace");
await snippets.Workspace.Initialization;
await snippets.Compile(SNIPPETS.HelloQ);
var whoMagic = new WhoMagic(snippets, new UnitTestLogger<WhoMagic>());
var channel = new MockChannel();
// Check the workspace, it should be in error state:
var response = await whoMagic.Execute("", channel);
var result = response.Output as string[];
PrintResult(response, channel);
response.AssertIsOk();
Assert.AreEqual(6, result?.Length);
Assert.AreEqual("HelloQ", result?[0]);
Assert.AreEqual("Tests.qss.NoOp", result?[4]);
}
[TestMethod]
public async Task TestWorkspace()
{
var engine = await Init("Workspace.Chemistry");
var snippets = engine.Snippets as Snippets;
Assert.IsNotNull(snippets);
var wsMagic = new WorkspaceMagic(snippets!.Workspace, new UnitTestLogger<WorkspaceMagic>());
var pkgMagic = new PackageMagic(snippets!.GlobalReferences, new UnitTestLogger<PackageMagic>());
var channel = new MockChannel();
var result = new string[0];
// Check the workspace, it should be in error state:
var response = await wsMagic.Execute("reload", channel);
PrintResult(response, channel);
Assert.AreEqual(ExecuteStatus.Error, response.Status);
response = await wsMagic.Execute("", channel);
PrintResult(response, channel);
Assert.AreEqual(ExecuteStatus.Error, response.Status);
// Try compiling a snippet that depends on a workspace that depends on the chemistry package:
response = await engine.ExecuteMundane(SNIPPETS.DependsOnChemistryWorkspace, channel);
PrintResult(response, channel);
Assert.AreEqual(ExecuteStatus.Error, response.Status);
Assert.AreEqual(0, channel.msgs.Count);
// Add dependencies:
response = await pkgMagic.Execute("mock.chemistry", channel);
PrintResult(response, channel);
response.AssertIsOk();
response = await pkgMagic.Execute("mock.research", channel);
PrintResult(response, channel);
response.AssertIsOk();
// Reload workspace:
response = await wsMagic.Execute("reload", channel);
PrintResult(response, channel);
response.AssertIsOk();
response = await wsMagic.Execute("", channel);
result = response.Output as string[];
PrintResult(response, channel);
response.AssertIsOk();
Assert.AreEqual(2, result?.Length);
// Compilation must work:
await AssertCompile(engine, SNIPPETS.DependsOnChemistryWorkspace, "DependsOnChemistryWorkspace");
// Check an invalid command
response = await wsMagic.Execute("foo", channel);
PrintResult(response, channel);
Assert.AreEqual(ExecuteStatus.Error, response.Status);
// Check that everything still works:
response = await wsMagic.Execute("", channel);
PrintResult(response, channel);
response.AssertIsOk();
}
[TestMethod]
public async Task TestResolver()
{
var snippets = Startup.Create<Snippets>("Workspace");
await snippets.Workspace.Initialization;
await snippets.Compile(SNIPPETS.HelloQ);
var resolver = new SymbolResolver(snippets);
// Intrinsics:
var symbol = resolver.Resolve("X");
Assert.IsNotNull(symbol);
Assert.AreEqual("Microsoft.Quantum.Intrinsic.X", symbol!.Name);
// FQN Intrinsics:
symbol = resolver.Resolve("Microsoft.Quantum.Intrinsic.X");
Assert.IsNotNull(symbol);
Assert.AreEqual("Microsoft.Quantum.Intrinsic.X", symbol!.Name);
// From namespace:
symbol = resolver.Resolve("Tests.qss.CCNOTDriver");
Assert.IsNotNull(symbol);
Assert.AreEqual("Tests.qss.CCNOTDriver", symbol!.Name);
symbol = resolver.Resolve("CCNOTDriver");
Assert.IsNotNull(symbol);
Assert.AreEqual("Tests.qss.CCNOTDriver", symbol!.Name);
// Snippets:
symbol = resolver.Resolve("HelloQ");
Assert.IsNotNull(symbol);
Assert.AreEqual("HelloQ", symbol!.Name);
// resolver is case sensitive:
symbol = resolver.Resolve("helloq");
Assert.IsNull(symbol);
// Invalid name
symbol = resolver.Resolve("foo");
Assert.IsNull(symbol);
}
[TestMethod]
public void TestResolveMagic()
{
var serviceProvider = Startup.CreateServiceProvider("Workspace.Broken");
var resolver = serviceProvider.GetRequiredService<IMagicSymbolResolver>();
// We use the null-forgiving operator on symbol below, as the C# 8
// nullable reference feature does not incorporate the result of
// Assert.IsNotNull.
var symbol = resolver.Resolve("%workspace");
Assert.IsNotNull(symbol);
Assert.AreEqual("%workspace", symbol!.Name);
symbol = resolver.Resolve("%package") as MagicSymbol;
Assert.IsNotNull(symbol);
Assert.AreEqual("%package", symbol!.Name);
Assert.IsNotNull(resolver.Resolve("%who"));
Assert.IsNotNull(resolver.Resolve("%simulate"));
symbol = resolver.Resolve("%foo");
Assert.IsNull(symbol);
// AzureClient-provided commands
Assert.IsNotNull(resolver.Resolve("%azure.connect"));
Assert.IsNotNull(resolver.Resolve("%azure.target"));
Assert.IsNotNull(resolver.Resolve("%azure.submit"));
Assert.IsNotNull(resolver.Resolve("%azure.execute"));
Assert.IsNotNull(resolver.Resolve("%azure.status"));
Assert.IsNotNull(resolver.Resolve("%azure.output"));
Assert.IsNotNull(resolver.Resolve("%azure.jobs"));
}
/// <summary>
/// Checks that the hint provided to users when a magic command fails
/// to resolve is correct.
/// </summary>
[TestMethod]
public async Task TestHintOnFailedMagic() =>
await Assert.That
.UsingEngine()
.Input("%lsmagi")
.ExecutesWithError(containing:
$@"
No such magic command %lsmagi.
Possibly similar magic commands:
- %lsmagic
- %lsopen
"
.Dedent().Trim());
[TestMethod]
public async Task TestDebugMagic()
{
var engine = await Init();
Assert.IsNotNull(engine.SymbolsResolver);
await AssertCompile(engine, SNIPPETS.SimpleDebugOperation, "SimpleDebugOperation");
var configSource = new ConfigurationSource(skipLoading: true);
var debugMagic = new DebugMagic(engine.SymbolsResolver!, configSource, engine.ShellRouter, engine.ShellServer, null);
// Start a debug session
var channel = new MockChannel();
var cts = new CancellationTokenSource();
var debugTask = debugMagic.RunAsync("SimpleDebugOperation", channel, cts.Token);
// Retrieve the debug session ID
var message = channel.iopubMessages[0];
Assert.IsNotNull(message);
Assert.AreEqual("iqsharp_debug_sessionstart", message.Header.MessageType);
var content = message.Content as DebugSessionContent;
Assert.IsNotNull(content);
var debugSessionId = content!.DebugSession;
// Send several iqsharp_debug_advance messages
var debugAdvanceMessage = new Message
{
Header = new MessageHeader
{
MessageType = "iqsharp_debug_advance"
},
Content = new UnknownContent
{
Data = new Dictionary<string, object>
{
["debug_session"] = debugSessionId
}
}
};
foreach (int _ in Enumerable.Range(0, 1000))
{
Thread.Sleep(millisecondsTimeout: 10);
if (debugTask.IsCompleted)
break;
await debugMagic.HandleAdvanceMessage(debugAdvanceMessage);
}
// Verify that the command completes successfully
Assert.IsTrue(debugTask.IsCompleted);
Assert.AreEqual(System.Threading.Tasks.TaskStatus.RanToCompletion, debugTask.Status);
// Ensure that expected messages were sent
try
{
Assert.AreEqual("iqsharp_debug_sessionstart", channel.iopubMessages[0].Header.MessageType);
Assert.AreEqual("iqsharp_debug_opstart", channel.iopubMessages[1].Header.MessageType);
Assert.AreEqual("iqsharp_debug_sessionend", channel.iopubMessages.Last().Header.MessageType);
}
catch (AssertFailedException ex)
{
await Console.Error.WriteLineAsync(
"IOPub messages sent by %debug were incorrect.\nReceived messages:\n" +
SessionAsString(channel.iopubMessages)
);
throw ex;
}
Assert.IsTrue(channel.msgs[0].Contains("Starting debug session"));
Assert.IsTrue(channel.msgs[1].Contains("Finished debug session"));
// Verify debug status content
var debugStatusContent = channel.iopubMessages[1].Content as DebugStatusContent;
Assert.IsNotNull(debugStatusContent?.State);
Assert.AreEqual(debugSessionId, debugStatusContent?.DebugSession);
}
[TestMethod]
public async Task TestDebugMagicCancel()
{
var engine = await Init();
// Since Init guarantees that engine services have started, we
// assert non-nullness here.
Assert.IsNotNull(engine.SymbolsResolver);
await AssertCompile(engine, SNIPPETS.SimpleDebugOperation, "SimpleDebugOperation");
var configSource = new ConfigurationSource(skipLoading: true);
// We asserted that SymbolsResolver is not null above, and can use
// the null-forgiving operator here as a result.
var debugMagic = new DebugMagic(engine.SymbolsResolver!, configSource, engine.ShellRouter, engine.ShellServer, null);
// Start a debug session
var channel = new MockChannel();
var cts = new CancellationTokenSource();
var debugTask = debugMagic.RunAsync("SimpleDebugOperation", channel, cts.Token);
// Cancel the session
cts.Cancel();
// Ensure that the task throws an exception
Assert.ThrowsException<AggregateException>(() => debugTask.Wait());
// Ensure that expected messages were sent
try
{
Assert.AreEqual("iqsharp_debug_sessionstart", channel.iopubMessages[0].Header.MessageType);
// Note that depending on how long it takes cancellation to run, we may encounter
// one or more IOPub messages corresponding to other debug session events.
Assert.AreEqual("iqsharp_debug_sessionend", channel.iopubMessages[channel.iopubMessages.Count - 1].Header.MessageType);
}
catch (AssertFailedException ex)
{
await Console.Error.WriteLineAsync(
"IOPub messages sent by %debug were incorrect.\nReceived messages:\n" +
SessionAsString(channel.iopubMessages)
);
throw ex;
}
Assert.IsTrue(channel.msgs[0].Contains("Starting debug session"));
Assert.IsTrue(channel.msgs[1].Contains("Finished debug session"));
}
[TestMethod]
public async Task TestTraceMagic()
{
await AssertTrace("FooCirc", new ExecutionPath(
new QubitDeclaration[] { new QubitDeclaration(0) },
new Operation[]
{
new Operation ()
{
Gate = "FooCirc",
Targets = new List<QubitRegister> () { new QubitRegister (0) },
Children = ImmutableList<Operation>.Empty.AddRange (
new [] {
new Operation () {
Gate = "Foo",
DisplayArgs = "(2.1, (\"bar\"))",
Targets = new List<Register> () { new QubitRegister (0) },
},
}
)
}
}
), 1);
// Depth 2
await AssertTrace("FooCirc --depth=2", new ExecutionPath(
new QubitDeclaration[] { new QubitDeclaration(0) },
new Operation[]
{
new Operation ()
{
Gate = "FooCirc",
Targets = new List<QubitRegister> () { new QubitRegister (0) },
Children = ImmutableList<Operation>.Empty.AddRange (
new [] {
new Operation () {
Gate = "Foo",
DisplayArgs = "(2.1, (\"bar\"))",
Targets = new List<Register> () { new QubitRegister (0) },
},
}
)
}
}
), 2);
}
[TestMethod]
public async Task CompileAndSubmitWithClassicalControl()
{
const string source = @"
open Microsoft.Quantum.Measurement;
operation PrepareBellPair(left : Qubit, right : Qubit) : Unit is Adj + Ctl {
H(left);
CNOT(left, right);
}
operation Teleport(msg : Qubit, target : Qubit) : Unit {
use register = Qubit();
PrepareBellPair(register, target);
Adjoint PrepareBellPair(msg, register);
if MResetZ(msg) == One { Z(target); }
if MResetZ(register) == One { X(target); }
}
operation RunTeleport() : Unit {
use left = Qubit();
use right = Qubit();
H(left);
Teleport(left, right);
H(right);
if M(right) == One {
fail ""Got wrong output from teleportation."";
}
}
";
var engineInput = await Assert.That
.UsingEngine()
.Input(source)
.ExecutesSuccessfully()
.WithMockAzure()
.Input("%azure.target quantinuum.mock")
.ExecutesSuccessfully()
.Input("%azure.submit RunTeleport")
.ExecutesSuccessfully()
.Input("%azure.target ionq.mock")
.ExecutesSuccessfully()
.Input("%azure.submit RunTeleport")
.ExecutesSuccessfully();
}
/// <summary>
/// Tests for regression against
/// <see href="https://github.com/microsoft/iqsharp/issues/606">
/// microsoft/iqsharp#606
/// </see>.
/// </summary>
[TestMethod]
public async Task CompileAndSimulateWithLambdas()
{
const string source = @"
function Foo() : Unit {
let f = x -> x;
let y = f(12);
}
operation DoBar() : Unit {
let u = (q) => H(q);
use q = Qubit();
H(q);
u(q);
}
";
var engineInput = await Assert.That
.UsingEngine()
.Input(source)
.ExecutesSuccessfully()
.Input("%simulate Foo")
.ExecutesSuccessfully()
.Input("%simulate DoBar")
.ExecutesSuccessfully();
}
}
}
#pragma warning restore VSTHRD200 // Use "Async" suffix for async methods
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously