-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathProjectSystemSteps.cs
More file actions
993 lines (869 loc) · 42.4 KB
/
ProjectSystemSteps.cs
File metadata and controls
993 lines (869 loc) · 42.4 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
#nullable disable
namespace Reqnroll.VisualStudio.Specs.StepDefinitions;
[Binding]
public class ProjectSystemSteps : Steps
{
private readonly StubIdeScope _ideScope;
private string _commandToInvokeDeferred;
private StubCompletionBroker _completionBroker;
private MockableDiscoveryService _discoveryService;
private DeveroomEditorCommandBase _invokedCommand;
private InMemoryStubProjectScope _projectScope;
private ProjectStepDefinitionBinding _stepDefinitionBinding;
private ProjectHookBinding _hookBinding;
private StubWpfTextView _wpfTextView;
private Random _rnd = new(42);
public ProjectSystemSteps(StubIdeScope stubIdeScope)
{
_ideScope = stubIdeScope;
_ideScope.SetupFireAndForgetOnBackgroundThread((action, callerName) => action(_ideScope.BackgroundTaskTokenSource.Token));
}
private StubIdeActions ActionsMock => (StubIdeActions)_ideScope.Actions;
[Given(@"there is a Reqnroll project scope")]
public void GivenThereIsAReqnrollProjectScope()
{
CreateProject(ps => ps.AddReqnrollPackage());
}
[Given("there is a non-Reqnroll project scope")]
public void GivenThereIsANon_ReqnrollProjectScope()
{
CreateProject(ps => ps.StubProjectSettingsProvider.Kind = DeveroomProjectKind.FeatureFileContainerProject);
}
[Given("there is a project scope which is (.*)")]
public void GivenThereIsAProjectScopeWhichIs(DeveroomProjectKind kind)
{
CreateProject(ps => ps.StubProjectSettingsProvider.Kind = kind);
}
private void CreateProject(Action<InMemoryStubProjectScope> initialize)
{
_projectScope = new InMemoryStubProjectScope(_ideScope);
initialize(_projectScope);
_discoveryService = MockableDiscoveryService.Setup(_projectScope, TimeSpan.FromMilliseconds(100));
}
[Given(@"there is a Reqnroll project scope with calculator step definitions")]
public void GivenThereIsAReqnrollProjectScopeWithCalculatorStepDefinitions()
{
GivenThereIsAReqnrollProjectScope();
var filePath = @"X:\ProjectMock\CalculatorSteps.cs";
_discoveryService.LastDiscoveryResult.StepDefinitions = new[]
{
new StepDefinition
{
Method = "GivenIHaveEnteredIntoTheCalculator",
ParamTypes = "i",
Type = "Given",
Regex = "^I have entered (.*) into the calculator$",
SourceLocation = filePath + "|24|5"
},
new StepDefinition
{
Method = "WhenIPressAdd",
Type = "When",
Regex = "^I press add$",
SourceLocation = filePath + "|12|5"
},
new StepDefinition
{
Method = "ThenTheResultShouldBeOnTheScreen",
ParamTypes = "i",
Type = "Then",
Regex = "^the result should be (.*) on the screen$",
SourceLocation = filePath + "|18|5"
}
};
_projectScope.AddFile(filePath, string.Empty);
}
[When("the reqnroll.json configuration file is updated to")]
public void WhenTheReqnrollJsonConfigurationFileContains(string configFileContent)
{
var configFileName = "reqnroll.json";
_projectScope.UpdateConfigFile(configFileName, configFileContent);
}
[Given(@"the reqnroll.json configuration file contains")]
public void GivenTheReqnrollJsonConfigurationFileContains(string configFileContent)
{
var configFileName = "reqnroll.json";
_projectScope
.UpdateConfigFile(configFileName, configFileContent);
InMemoryStubProjectBuilder.CreateOutputAssembly(_projectScope);
_ideScope.TriggerProjectsBuilt();
}
[Given(@"the project is configured for SpecSync with Azure DevOps project URL ""([^""]*)""")]
public void GivenTheProjectIsConfiguredForSpecSyncWithAzureDevOpsProjectUrl(string projectUrl)
{
string specSyncConfigFileContent = @"{
'remote': {
'projectUrl': '" + projectUrl + @"',
}
}";
_projectScope
.UpdateConfigFile("specsync.json", specSyncConfigFileContent);
InMemoryStubProjectBuilder.CreateOutputAssembly(_projectScope);
_ideScope.TriggerProjectsBuilt();
}
[When(@"a new step definition is added to the project as:")]
[Given(@"the following step definitions in the project:")]
public void WhenANewStepDefinitionIsAddedToTheProjectAs(Table stepDefinitionTable)
{
var stepDefinitions = stepDefinitionTable.CreateSet(CreateStepDefinitionFromTableRow).ToArray();
RegisterStepDefinitions(stepDefinitions);
}
[Given(@"the following step definition with mulitple Tag Scopes in the project:")]
public void GivenNewStepDefinitionsWithMultipleScopeTagsAreAddedToTheProjectAs(Table stepDefinitionTable)
{
var stepDefinitions = stepDefinitionTable.CreateSet(CreateStepDefinitionFromTableRow).ToArray();
var resultingStepDefinitions = new List<StepDefinition>();
// we expect that the Tag scope string in the table is a comma delimited set of tags to apply;
// So we will create a step definition for each such tag by using the built step def as a template.
foreach (var sd in stepDefinitions)
{
var taglist = sd.Scope.Tag.Split(',');
foreach (var t in taglist)
{
var stepDefToAdd = new StepDefinition
{
Type = sd.Type,
Method = sd.Method,
Regex = sd.Regex,
SourceLocation = sd.SourceLocation,
Scope = new StepScope
{
Tag = t,
FeatureTitle = sd.Scope.FeatureTitle,
ScenarioTitle = sd.Scope.ScenarioTitle
}
};
resultingStepDefinitions.Add(stepDefToAdd);
}
}
RegisterStepDefinitions(resultingStepDefinitions.ToArray());
}
[Given("the following hooks in the project:")]
public void GivenTheFollowingHooksInTheProject(DataTable hooksTable)
{
var hooks = hooksTable.CreateSet(CreateHookFromTableRow).ToArray();
RegisterHooks(hooks);
}
private StepDefinition CreateStepDefinitionFromTableRow(DataTableRow tableRow)
{
var filePath = @"X:\ProjectMock\CalculatorSteps.cs";
var line = _rnd.Next(1, 30);
_projectScope.AddFile(filePath, string.Empty);
tableRow.TryGetValue("regex", out var regex);
tableRow.TryGetValue("type", out var stepType);
var stepDefinition = new StepDefinition
{
Method = $"M{Guid.NewGuid():N}",
SourceLocation = filePath + $"|{line}|5"
};
tableRow.TryGetValue("tag scope", out var tagScopes);
tableRow.TryGetValue("feature scope", out var featureScope);
tableRow.TryGetValue("scenario scope", out var scenarioScope);
if (string.IsNullOrEmpty(tagScopes))
tagScopes = null;
if (string.IsNullOrEmpty(featureScope))
featureScope = null;
if (string.IsNullOrEmpty(scenarioScope))
scenarioScope = null;
if (tagScopes != null || featureScope != null || scenarioScope != null)
stepDefinition.Scope = new StepScope
{
Tag = tagScopes,
FeatureTitle = featureScope,
ScenarioTitle = scenarioScope
};
return stepDefinition;
}
private Hook CreateHookFromTableRow(DataTableRow tableRow)
{
var filePath = @"X:\ProjectMock\Hooks.cs";
var line = _rnd.Next(1, 30);
var hook = new Hook
{
Method = $"M{Guid.NewGuid():N}",
SourceLocation = filePath + $"|{line}|8"
};
tableRow.TryGetValue("tag scope", out var tagScope);
tableRow.TryGetValue("feature scope", out var featureScope);
tableRow.TryGetValue("scenario scope", out var scenarioScope);
if (string.IsNullOrEmpty(tagScope))
tagScope = null;
if (string.IsNullOrEmpty(featureScope))
featureScope = null;
if (string.IsNullOrEmpty(scenarioScope))
scenarioScope = null;
if (tagScope != null || featureScope != null || scenarioScope != null)
hook.Scope = new StepScope
{
Tag = tagScope,
FeatureTitle = featureScope,
ScenarioTitle = scenarioScope
};
_projectScope.AddFile(filePath, string.Empty);
return hook;
}
private void RegisterStepDefinitions(params StepDefinition[] stepDefinitions)
{
_discoveryService.LastDiscoveryResult = new DiscoveryResult
{
StepDefinitions = _discoveryService.LastDiscoveryResult.StepDefinitions.Concat(stepDefinitions).ToArray(),
Hooks = _discoveryService.LastDiscoveryResult.Hooks
};
}
private void RegisterHooks(params Hook[] hooks)
{
_discoveryService.LastDiscoveryResult = new DiscoveryResult
{
StepDefinitions = _discoveryService.LastDiscoveryResult.StepDefinitions,
Hooks = _discoveryService.LastDiscoveryResult.Hooks.Concat(hooks).ToArray()
};
}
[Given(@"^the following C\# step definition class$")]
[Given(@"^the following C\# step definition class in the editor$")]
public void GivenTheFollowingCStepDefinitionClassInTheEditor(string stepDefinitionClass)
{
var fileName = DomainDefaults.StepDefinitionFileName;
var filePath = Path.Combine(_projectScope.ProjectFolder, fileName);
var stepDefinitionFile = GetStepDefinitionFileContentFromClass(stepDefinitionClass);
_projectScope.FilesAdded[filePath] = stepDefinitionFile;
var stepDefinitions = ParseStepDefinitions(stepDefinitionFile, filePath);
RegisterStepDefinitions(stepDefinitions.ToArray());
_ideScope.TextViewFactory = (TestText inputText, string path) =>
_ideScope.BasicTextViewFactory(inputText, path, VsContentTypes.CSharp);
_wpfTextView =
_ideScope.CreateTextView(new TestText(stepDefinitionFile), filePath) as
StubWpfTextView;
}
private static string GetStepDefinitionFileContentFromClass(string stepDefinitionClass) =>
string.Join(Environment.NewLine, "using System;", "using Reqnroll;", "", "namespace MyProject",
"{", stepDefinitionClass, "}");
private static string GetStepDefinitionClassFromMethod(string stepDefinitionMethod) =>
string.Join(Environment.NewLine, "[Binding]", "public class StepDefinitions1", "{", stepDefinitionMethod,
"}");
private List<StepDefinition> ParseStepDefinitions(string stepDefinitionFileContent, string filePath)
{
var stepDefinitions = new List<StepDefinition>();
var tree = CSharpSyntaxTree.ParseText(stepDefinitionFileContent);
var rootNode = tree.GetRoot();
var nsDeclaration = rootNode.DescendantNodes().OfType<NamespaceDeclarationSyntax>().First();
var methods = rootNode.DescendantNodes().OfType<MethodDeclarationSyntax>().ToArray();
foreach (var method in methods)
{
var classDeclarationSyntax = method.Ancestors().OfType<ClassDeclarationSyntax>().First();
Debug.Assert(method.Body != null);
var methodLineNumber = method.SyntaxTree.GetLineSpan(method.Body.Span).StartLinePosition.Line + 1;
var stepDefinitionAttributes =
RenameStepStepDefinitionClassAction.GetAttributesWithTokens(method)
.Where(awt => !awt.Item2.IsMissing)
.ToArray();
foreach (var (attributeSyntax, stepDefinitionAttributeTextToken) in stepDefinitionAttributes)
{
var stepDefinition = new StepDefinition
{
Regex = "^" + stepDefinitionAttributeTextToken.ValueText + "$",
Method = $"{nsDeclaration.Name}.{classDeclarationSyntax.Identifier.Text}.{method.Identifier.Text}",
ParamTypes = "",
Type = attributeSyntax?.Name.ToString(),
SourceLocation = $"{filePath}|{methodLineNumber}|1",
Expression = stepDefinitionAttributeTextToken.ValueText
};
_ideScope.Logger.LogInfo(
$"{stepDefinition.SourceLocation}: {stepDefinition.Type}/{stepDefinition.Regex}");
stepDefinitions.Add(stepDefinition);
}
}
return stepDefinitions;
}
[When(@"the project is built")]
[When("the project is built and the initial binding discovery is performed")]
[Given("the project is built and the initial binding discovery is performed")]
public async Task GivenTheProjectIsBuiltAndTheInitialBindingDiscoveryIsPerformed()
{
await InMemoryStubProjectBuilder.BuildAndWaitBackGroundTasks(_projectScope);
}
[Given(@"the following feature file ""([^""]*)""")]
public void GivenTheFollowingFeatureFile(string fileName, string fileContent)
{
var filePath = Path.Combine(_projectScope.ProjectFolder, fileName);
_ideScope.FileSystem.Directory.CreateDirectory(_projectScope.ProjectFolder);
_ideScope.FileSystem.File.WriteAllText(filePath, fileContent);
_projectScope.FilesAdded[filePath] = fileContent;
}
[Given(@"the following feature file in the editor")]
[When(@"the following feature file is opened in the editor")]
public void GivenTheFollowingFeatureFileInTheEditor(string featureFileContent)
{
var fileName = "Feature1.feature";
var filePath = Path.Combine(_projectScope.ProjectFolder, fileName);
_projectScope.FilesAdded[filePath] = featureFileContent;
_ideScope.TextViewFactory = (TestText inputText, string path) =>
_ideScope.BasicTextViewFactory(inputText, path, VsContentTypes.FeatureFile);
_wpfTextView =
_ideScope.CreateTextView(new TestText(featureFileContent), filePath) as
StubWpfTextView;
GivenTheFollowingFeatureFile(fileName, _wpfTextView.TextBuffer.CurrentSnapshot.GetText());
CreateTagAggregator();
}
[When(@"I invoke the ""(.*)"" command by typing ""(.*)""")]
public void WhenIInvokeTheCommandByTyping(string commandName, string typedText)
{
PerformCommand(commandName, typedText);
}
[Given(@"the ""(.*)"" command has been invoked")]
[When(@"I invoke the ""(.*)"" command")]
public void WhenIInvokeTheCommand(string commandName)
{
PerformCommand(commandName);
}
[When(@"I invoke the ""(.*)"" command without waiting for the tag changes")]
public void WhenIInvokeTheCommandWithoutWaitingForTagger(string commandName)
{
PerformCommand(commandName, waitForTager: false);
}
private void PerformCommand(string commandName, string parameter = null,
DeveroomEditorCommandTargetKey? commandTargetKey = null, bool waitForTager = true)
{
ActionsMock.ResetMock();
var taggerProvider = CreateTaggerProvider();
ManualResetEvent tagged = new ManualResetEvent(false);
var tagger = taggerProvider.CreateTagger<DeveroomTag>(_ideScope.CurrentTextView.TextBuffer);
tagger.TagsChanged += (object sender, SnapshotSpanEventArgs e) => { tagged.Set(); };
var aggregatorFactoryService = new StubBufferTagAggregatorFactoryService(taggerProvider);
switch (commandName)
{
case "Go To Definition":
{
_invokedCommand = new GoToDefinitionCommand(
_ideScope,
aggregatorFactoryService,
taggerProvider);
_invokedCommand.PreExec(_wpfTextView, _invokedCommand.Targets.First());
return;
}
case "Go To Hooks":
{
_invokedCommand = new GoToHooksCommand(
_ideScope,
aggregatorFactoryService,
taggerProvider);
_invokedCommand.PreExec(_wpfTextView, _invokedCommand.Targets.First());
return;
}
case "Find Step Definition Usages":
{
_invokedCommand = new FindStepDefinitionUsagesCommand(
_ideScope,
aggregatorFactoryService,
taggerProvider);
_invokedCommand.PreExec(_wpfTextView, _invokedCommand.Targets.First());
Wait.For(() => ActionsMock.IsComplete.Should().BeTrue());
return;
}
case "Find Unused Step Definitions":
{
_invokedCommand = new FindUnusedStepDefinitionsCommand(
_ideScope,
aggregatorFactoryService,
taggerProvider);
_invokedCommand.PreExec(_wpfTextView, _invokedCommand.Targets.First());
Wait.For(() => ActionsMock.IsComplete.Should().BeTrue());
return;
}
case "Comment":
{
_invokedCommand = new CommentCommand(
_ideScope,
aggregatorFactoryService,
taggerProvider);
_invokedCommand.PreExec(_wpfTextView, _invokedCommand.Targets.First());
break;
}
case "Uncomment":
{
_invokedCommand = new UncommentCommand(
_ideScope,
aggregatorFactoryService,
taggerProvider);
_invokedCommand.PreExec(_wpfTextView, _invokedCommand.Targets.First());
break;
}
case "Auto Format Document":
{
_invokedCommand = new AutoFormatDocumentCommand(
_ideScope,
aggregatorFactoryService,
taggerProvider,
new GherkinDocumentFormatter(),
new StubEditorConfigOptionsProvider());
_invokedCommand.PreExec(_wpfTextView, AutoFormatDocumentCommand.FormatDocumentKey);
break;
}
case "Auto Format Selection":
{
_invokedCommand = new AutoFormatDocumentCommand(
_ideScope,
aggregatorFactoryService,
taggerProvider,
new GherkinDocumentFormatter(),
new StubEditorConfigOptionsProvider());
_invokedCommand.PreExec(_wpfTextView, AutoFormatDocumentCommand.FormatSelectionKey);
break;
}
case "Auto Format Table":
{
_invokedCommand = new AutoFormatTableCommand(
_ideScope,
aggregatorFactoryService,
taggerProvider,
new GherkinDocumentFormatter(),
new StubEditorConfigOptionsProvider());
_wpfTextView.SimulateType((AutoFormatTableCommand)_invokedCommand, parameter?[0] ?? '|',
taggerProvider);
break;
}
case "Define Steps":
{
_invokedCommand = new DefineStepsCommand(_ideScope, aggregatorFactoryService, taggerProvider);
_invokedCommand.PreExec(_wpfTextView, _invokedCommand.Targets.First());
return;
}
case "Complete":
case "Filter Completion":
{
EnsureStubCompletionBroker();
_invokedCommand = new CompleteCommand(
_ideScope,
aggregatorFactoryService,
taggerProvider,
_completionBroker);
if (parameter == null)
{
_invokedCommand.PreExec(_wpfTextView, commandTargetKey ?? _invokedCommand.Targets.First());
return;
}
else
_wpfTextView.SimulateTypeText((CompleteCommand)_invokedCommand, parameter, taggerProvider);
break;
}
case "Rename Step":
{
_invokedCommand = new RenameStepCommand(
_ideScope,
aggregatorFactoryService,
taggerProvider);
_invokedCommand.PreExec(_wpfTextView, _invokedCommand.Targets.First());
break;
}
default:
throw new NotImplementedException(commandName);
}
if (waitForTager)
tagged.WaitOne(TimeSpan.FromSeconds(5)).Should().BeTrue($"{commandName}({parameter}) haven't triggered a text change");
}
private StubBufferTagAggregatorFactoryService CreateAggregatorFactory() => new(CreateTaggerProvider());
private IDeveroomTaggerProvider CreateTaggerProvider()
{
var taggerProvider = new DeveroomTaggerProvider(_ideScope, new SpecFlowExtensionDetection.SpecFlowExtensionDetectionService(_ideScope));
var tagger = taggerProvider.CreateTagger<DeveroomTag>(_ideScope.CurrentTextView.TextBuffer);
var span = new SnapshotSpan(_ideScope.CurrentTextView.TextSnapshot, 0, 0);
tagger.GetUpToDateDeveroomTagsForSpan(span);
return taggerProvider;
}
private void EnsureStubCompletionBroker()
{
if (_completionBroker != null)
return;
var textBuffer = _wpfTextView.TextBuffer;
var completionSource = new DeveroomCompletionSource(
textBuffer,
CreateAggregatorFactory().CreateTagAggregator<DeveroomTag>(textBuffer),
_ideScope);
_completionBroker = new StubCompletionBroker(completionSource);
}
[When(@"when the command is finished")]
private async Task WhenTheCommandIsFinished()
{
using var cts = new DebuggableCancellationTokenSource(TimeSpan.FromSeconds(10));
await _invokedCommand.Finished.WaitAsync(cts.Token);
}
[When(@"commit the ""([^""]*)"" completion item")]
public void WhenCommitTheCompletionItem(string value)
{
EnsureStubCompletionBroker();
//TODO: select item
var session = _completionBroker.GetSessions(_wpfTextView).FirstOrDefault();
session.Should().NotBeNull("There should be an active completion session");
var completionSet = session.SelectedCompletionSet;
completionSet.Should().NotBeNull("There should be an active completion set");
var completion = completionSet.Completions.FirstOrDefault(c => c.InsertionText.StartsWith(value));
completion.Should().NotBeNull($"There should be a completion item starting with '{value}'");
completionSet.SelectionStatus =
new CompletionSelectionStatus(completion, true, true);
PerformCommand("Complete", null, CompletionCommandBase.ReturnCommand);
}
[Then(@"the editor should be updated to")]
public void ThenTheEditorShouldBeUpdatedTo(string expectedContentValue)
{
var expectedContent = new TestText(expectedContentValue);
Assert.Equal(expectedContent.ToString(), _wpfTextView.TextSnapshot.GetText());
}
[Then("the editor should be updated to contain")]
public void ThenTheEditorShouldBeUpdatedToContain(string expectedContentValue)
{
var expectedContent = new TestText(expectedContentValue).ToString();
var currentContent = _ideScope.CurrentTextView.TextSnapshot.GetText();
currentContent.Should().Contain(expectedContent);
}
private IEnumerable<DeveroomTag> GetDeveroomTags(IWpfTextView textView)
{
var tagger = CreateTaggerProvider().CreateTagger<DeveroomTag>(textView.TextBuffer);
var span = new SnapshotSpan(textView.TextSnapshot, 0, textView.TextSnapshot.Length);
return tagger.GetUpToDateDeveroomTagsForSpan(span).Select(t => t.Tag);
}
private IEnumerable<ITagSpan<TTag>> GetVsTagSpans<TTag>(IWpfTextView textView, ITaggerProvider taggerProvider)
where TTag : ITag
{
var tagger = taggerProvider.CreateTagger<TTag>(textView.TextBuffer);
return GetVsTagSpans<TTag, ITagger<TTag>>(textView, tagger);
}
private IEnumerable<ITagSpan<TTag>> GetVsTagSpans<TTag, TTagger>(IWpfTextView textView, TTagger tagger)
where TTag : ITag where TTagger : ITagger<TTag>
{
var spans = new NormalizedSnapshotSpanCollection(new SnapshotSpan(textView.TextSnapshot, 0,
textView.TextSnapshot.Length));
return tagger.GetTags(spans);
}
[Then(@"all section of types (.*) should be highlighted as")]
public void ThenAllSectionOfTypesShouldBeHighlightedAs(string[] keywordTypes, string expectedContent)
{
CreateTagAggregator();
var expectedContentText = new TestText(expectedContent);
var tags = GetDeveroomTags(_wpfTextView).Where(t => keywordTypes.Contains(t.Type)).ToArray();
var testTextSections = expectedContentText.Sections.Where(s => keywordTypes.Contains(s.Label)).ToArray();
testTextSections.Should().NotBeEmpty("there should be something to expect");
var matchedTags = tags.ToList();
foreach (var section in testTextSections)
{
var matchedTag = tags.FirstOrDefault(
t =>
t.Type == section.Label &&
t.Span.Start == expectedContentText.GetSnapshotPoint(t.Span.Snapshot, section.Start.Line,
section.Start.Column) &&
t.Span.End ==
expectedContentText.GetSnapshotPoint(t.Span.Snapshot, section.End.Line, section.End.Column)
);
matchedTag.Should().NotBeNull($"the section '{section}' should be highlighted");
matchedTags.Remove(matchedTag);
}
matchedTags.Should().BeEmpty();
}
[Then("there are no sections of type (.*)")]
public void ThenThereAreNoSectionsOfTypeUndefinedStep(string[] keywordTypes)
{
CreateTagAggregator();
var allTags = GetDeveroomTags(_wpfTextView).ToArray();
var tags = allTags.Where(t => keywordTypes.Contains(t.Type)).ToArray();
allTags.Should().NotBeEmpty();
tags.Should().BeEmpty();
}
private ITagAggregator<DeveroomTag> CreateTagAggregator()
{
var textView = _ideScope.CurrentTextView;
ITagAggregator<DeveroomTag> tagAggregator =
CreateAggregatorFactory().CreateTagAggregator<DeveroomTag>(textView.TextBuffer);
tagAggregator.GetTags(new SnapshotSpan(textView.TextSnapshot, 0, textView.TextSnapshot.Length)).ToArray();
return tagAggregator;
}
[Then(@"no binding error should be highlighted")]
public void ThenNoBindingErrorShouldBeHighlighted()
{
var tags = GetDeveroomTags(_wpfTextView).ToArray();
tags.Should().NotContain(t => t.Type == "BindingError");
}
[Then(@"all (.*) section should be highlighted as")]
public void ThenTheStepKeywordsShouldBeHighlightedAs(string keywordType, string expectedContent)
{
ThenAllSectionOfTypesShouldBeHighlightedAs(new[] { keywordType }, expectedContent);
}
[Then(@"the tag links should target to the following URLs")]
public void ThenTheTagLinksShouldTargetToTheFollowingURLs(Table expectedTagLinksTable)
{
var tagSpans = GetVsTagSpans<UrlTag>(_wpfTextView,
new DeveroomUrlTaggerProvider(CreateAggregatorFactory(), _ideScope)).ToArray();
var actualTagLinks = tagSpans.Select(t => new { Tag = t.Span.GetText(), URL = t.Tag.Url.ToString() });
expectedTagLinksTable.CompareToSet(actualTagLinks);
}
[Then(@"the source file of the ""(.*)"" ""(.*)"" step definition is opened")]
public void ThenTheSourceFileOfTheStepDefinitionIsOpened(string stepRegex, Reqnroll.VisualStudio.Editor.Services.Parser.ScenarioBlock stepType)
{
_stepDefinitionBinding = _discoveryService.BindingRegistryCache.Value.StepDefinitions
.FirstOrDefault(b => b.StepDefinitionType == stepType && b.Regex.ToString().Contains(stepRegex));
_stepDefinitionBinding.Should().NotBeNull($"there has to be a {stepType} stepdef with regex '{stepRegex}'");
ActionsMock.LastNavigateToSourceLocation.Should().NotBeNull();
ActionsMock.LastNavigateToSourceLocation.SourceFile.Should()
.Be(_stepDefinitionBinding.Implementation.SourceLocation!.SourceFile);
}
[Then("the source file of the {string} hook is opened")]
public void ThenTheSourceFileOfTheHookIsOpened(string hookMethodName)
{
_hookBinding = _discoveryService.BindingRegistryCache.Value.Hooks
.FirstOrDefault(b => b.Implementation.Method == hookMethodName);
_hookBinding.Should().NotBeNull($"there has to be a {hookMethodName} hook");
ActionsMock.LastNavigateToSourceLocation.Should().NotBeNull();
ActionsMock.LastNavigateToSourceLocation.SourceFile.Should()
.Be(_hookBinding.Implementation.SourceLocation!.SourceFile);
ActionsMock.LastNavigateToSourceLocation.SourceFileLine.Should()
.Be(_hookBinding.Implementation.SourceLocation!.SourceFileLine);
}
[Then(@"the caret is positioned to the step definition method")]
public void ThenTheCaretIsPositionedToTheStepDefinitionMethod()
{
ActionsMock.LastNavigateToSourceLocation.Should().Be(_stepDefinitionBinding.Implementation.SourceLocation);
}
[Then(@"a jump list ""(.*)"" is opened with the following items")]
public void ThenAJumpListIsOpenedWithTheFollowingItems(string expectedHeader, Table expectedJumpListItemsTable)
{
ActionsMock.LastShowContextMenuHeader.Should().Be(expectedHeader);
ActionsMock.LastShowContextMenuItems.Should().NotBeNull();
var actualStepDefs = ActionsMock.LastShowContextMenuItems.Select(
i =>
new StepDefinitionJumpListData
{
StepDefinition = Regex.Match(i.Label, @"\((?<stepdef>.*?)\)").Groups["stepdef"].Value,
StepType = Regex.Match(i.Label, @"\[(?<stepdeftype>.*?)\(").Groups["stepdeftype"].Value,
Hook = Regex.Match(i.Label, @"\]\:\s*(?<hook>.*)").Groups["hook"].Value,
HookScope = Regex.Match(i.Label, @"\((?<hookScope>.*?)\)").Groups["hookScope"].Value,
HookType = Regex.Match(i.Label, @"\[(?<hookType>.*?)[\(\]]").Groups["hookType"].Value,
}).ToArray();
expectedJumpListItemsTable.CompareToSet(actualStepDefs, true);
}
[Then(@"a jump list ""(.*)"" is opened with the following steps")]
public void ThenAJumpListIsOpenedWithTheFollowingSteps(string expectedHeader, Table expectedJumpListItemsTable)
{
var expectedStepDefinitions = expectedJumpListItemsTable.Rows.Select(r => r[0]).ToArray();
ActionsMock.LastShowContextMenuHeader.Should().Be(expectedHeader);
ActionsMock.LastShowContextMenuItems.Should().NotBeNull();
var actualStepDefs = ActionsMock.LastShowContextMenuItems.Select(i => i.Label).ToArray();
actualStepDefs.Should().Equal(expectedStepDefinitions);
}
private void InvokeFirstContextMenuItem()
{
var firstItem = ActionsMock.LastShowContextMenuItems.ElementAtOrDefault(0);
firstItem.Should().NotBeNull();
// invoke the command
firstItem.Command(firstItem);
}
[Then(@"invoking the first item from the jump list navigates to the ""(.*)"" ""(.*)"" step definition")]
public void ThenInvokingTheFirstItemFromTheJumpListNavigatesToTheStepDefinition(string stepRegex,
Reqnroll.VisualStudio.Editor.Services.Parser.ScenarioBlock stepType)
{
InvokeFirstContextMenuItem();
ThenTheSourceFileOfTheStepDefinitionIsOpened(stepRegex, stepType);
}
[Then("invoking the first item from the jump list navigates to the {string} hook")]
public void ThenInvokingTheFirstItemFromTheJumpListNavigatesToTheHook(string hookMethodName)
{
InvokeFirstContextMenuItem();
ThenTheSourceFileOfTheHookIsOpened(hookMethodName);
}
[Then(@"invoking the first item from the jump list navigates to the ""([^""]*)"" step in ""([^""]*)"" line (.*)")]
public void ThenInvokingTheFirstItemFromTheJumpListNavigatesToTheStepInLine(string step, string expectedFile,
int expectedLine)
{
InvokeFirstContextMenuItem();
ActionsMock.LastNavigateToSourceLocation.Should().NotBeNull();
ActionsMock.LastNavigateToSourceLocation.SourceFile.Should().EndWith(expectedFile);
ActionsMock.LastNavigateToSourceLocation.SourceFileLine.Should().Be(expectedLine);
}
[Then(@"the step definition skeleton for the ""(.*)"" ""(.*)"" step should be offered to copy to clipboard")]
public void ThenTheStepDefinitionSkeletonForTheStepShouldBeOfferedToCopyToClipboard(string stepText,
Reqnroll.ScenarioBlock stepType)
{
ActionsMock.LastShowQuestion.Should().NotBeNull();
ActionsMock.LastShowQuestion.Description.Should().Contain(stepText);
ActionsMock.LastShowQuestion.Description.Should().Contain(stepType.ToString());
ActionsMock.LastShowQuestion.YesCommand.Should().NotBeNull();
}
[Then(@"there should be no navigation actions performed")]
public void ThenThereShouldBeNoNavigationActionsPerformed()
{
// neither navigation nor jump list
ActionsMock.LastNavigateToSourceLocation.Should().BeNull();
ActionsMock.LastShowContextMenuItems.Should().BeNull();
}
private StepDefinitionSnippetData[] ParseSnippetsFromFile(string text,
string filePath = DomainDefaults.StepDefinitionFileName)
{
var stepDefinitions = ParseStepDefinitions(text, filePath);
return stepDefinitions.Select(sd =>
new StepDefinitionSnippetData
{
Type = sd.Type,
Regex = sd.Regex,
Expression = sd.Expression,
Method = sd.Method
}).ToArray();
}
private StepDefinitionSnippetData[] ParseSnippets(string snippetText) =>
ParseSnippetsFromFile(
GetStepDefinitionFileContentFromClass(GetStepDefinitionClassFromMethod(snippetText)));
[Then(@"the define steps dialog should be opened with the following step definition skeletons")]
public void ThenTheDefineStepsDialogShouldBeOpenedWithTheFollowingStepDefinitionSkeletons(Table expectedSkeletons)
{
var viewModel = _ideScope.StubWindowManager.GetShowDialogViewModel<CreateStepDefinitionsDialogViewModel>();
viewModel.Should().NotBeNull("the 'define steps' dialog should have been opened");
var parsedSnippets = viewModel.Items.Select(i => ParseSnippets(i.Snippet).First()).ToArray();
expectedSkeletons.CompareToSet(parsedSnippets);
}
[Then(@"a (.*) dialog should be opened with ""(.*)""")]
public void ThenAShowProblemDialogShouldBeOpenedWith(string expectedDialog, string expectedMessage)
{
_ideScope.StubLogger.Logs.Should()
.Contain(m => m.CallerMethod.Contains(expectedDialog) && m.Message.Contains(expectedMessage));
}
[Given(@"the ""(.*)"" command is being invoked")]
public void GivenTheCommandIsBeingInvoked(string command)
{
_commandToInvokeDeferred = command;
}
[When(@"I select the step definition snippets (.*)")]
public void WhenISelectTheStepDefinitionSnippets(int[] indicesToSelect)
{
_ideScope.StubWindowManager.RegisterWindowAction<CreateStepDefinitionsDialogViewModel>(
viewModel =>
{
foreach (var item in viewModel.Items)
item.IsSelected = false;
foreach (var i in indicesToSelect)
viewModel.Items[i].IsSelected = true;
});
}
[When(@"close the define steps dialog with ""(.*)""")]
public async Task WhenCloseTheDefineStepsDialogWith(string button)
{
_ideScope.StubWindowManager.RegisterWindowAction<CreateStepDefinitionsDialogViewModel>(
viewModel =>
{
switch (button.ToLowerInvariant())
{
case "copy to clipboard":
viewModel.Result = CreateStepDefinitionsDialogResult.CopyToClipboard;
break;
case "create":
viewModel.Result = CreateStepDefinitionsDialogResult.Create;
break;
}
});
WhenIInvokeTheCommand(_commandToInvokeDeferred);
await WhenTheCommandIsFinished();
_projectScope.StubIdeScope.AnalyticsTransmitter
.Should()
.Contain(e => e.EventName == "DefineSteps command executed", "the command is finished");
}
[When("I specify {string} as renamed step")]
public async Task WhenISpecifyAsRenamedStep(string renamedStep)
{
_ideScope.StubWindowManager.RegisterWindowAction<RenameStepViewModel>(
viewModel => { viewModel.StepText = renamedStep; });
PerformCommand(_commandToInvokeDeferred, waitForTager: false);
await WhenTheCommandIsFinished();
_projectScope.StubIdeScope.AnalyticsTransmitter
.Should()
.Contain(e => e.EventName == "Rename step command executed", "the command is finished");
}
[Then("invoking the first item from the jump list renames the {string} {string} step definition")]
public async Task ThenInvokingTheFirstItemFromTheJumpListRenamesTheStepDefinition(string expression,
string stepType)
{
const string renamedExpression = "renamed step";
_ideScope.StubWindowManager.RegisterWindowAction<RenameStepViewModel>(
viewModel =>
{
viewModel.StepText = renamedExpression;
viewModel.OriginalStepText.Should()
.Be($"[{stepType}({expression})]: MyProject.CalculatorSteps.WhenIPressAdd");
});
InvokeFirstContextMenuItem();
await WhenTheCommandIsFinished();
string fileContent = _wpfTextView.TextSnapshot.GetText();
var parsedSnippets = ParseSnippetsFromFile(fileContent);
parsedSnippets.Should().Contain(s => s.Type == stepType && s.Expression == renamedExpression);
}
[Then(@"the following step definition snippets should be copied to the clipboard")]
public void ThenTheFollowingStepDefinitionSnippetsShouldBeCopiedToTheClipboard(Table expectedSnippets)
{
ActionsMock.ClipboardText.Should().NotBeNull("snippets should have been copied to clipboard");
var parsedSnippets = ParseSnippets(ActionsMock.ClipboardText);
expectedSnippets.CompareToSet(parsedSnippets);
}
[Then(@"the editor should be updated to contain the following step definitions")]
[Then(@"the following step definition snippets should be in the step definition class")]
public void ThenTheFollowingStepDefinitionSnippetsShouldBeInTheStepDefinitionClass(Table expectedSnippets)
{
ThenTheFollowingStepDefinitionSnippetsShouldBeInFile(DomainDefaults.StepDefinitionFileName, expectedSnippets);
}
[Then(@"the following step definition snippets should be in file ""(.*)""")]
public void ThenTheFollowingStepDefinitionSnippetsShouldBeInFile(string fileName, Table expectedSnippets)
{
string fileContent = GetActualContent(fileName);
var filePath = Path.Combine(_projectScope.ProjectFolder, fileName);
_projectScope.AddFile(filePath, fileContent);
var parsedSnippets = ParseSnippetsFromFile(fileContent, filePath);
expectedSnippets.CompareToSet(parsedSnippets);
}
[Then(@"a completion list should pop up with the following items")]
[Then(@"a completion list should list the following items")]
public void ThenACompletionListShouldPopUpWithTheFollowingItems(Table expectedItemsTable)
{
CheckCompletions(expectedItemsTable);
}
[Then(@"a completion list should pop up with the following keyword items")]
public void ThenACompletionListShouldPopUpWithTheFollowingKeywordItems(Table expectedItemsTable)
{
CheckCompletions(expectedItemsTable, t => char.IsLetter(t[0]));
}
[Then(@"a completion list should pop up with the following markers")]
public void ThenACompletionListShouldPopUpWithTheFollowingMarkers(Table expectedItemsTable)
{
CheckCompletions(expectedItemsTable, t => t.All(c => !char.IsLetter(c)));
}
private void CheckCompletions(Table expectedItemsTable, Func<string, bool> filter = null)
{
_completionBroker.Should().NotBeNull();
var actualCompletions = _completionBroker.Completions
.Where(c => filter?.Invoke(c.InsertionText) ?? true)
.Select(c => new { Item = c.InsertionText.Trim(), c.Description });
expectedItemsTable.CompareToSet(actualCompletions);
}
[Then("the file {string} should be updated to")]
public void ThenTheFileShouldBeUpdatedTo(string fileName, string expectedFileContent)
{
var actualContent = GetActualContent(fileName);
Assert.Equal(expectedFileContent, actualContent);
}
private string GetActualContent(string fileName)
{
var filePath = Path.Combine(_projectScope.ProjectFolder, fileName);
if (_ideScope.OpenViews.TryGetValue(filePath, out var textView))
return textView.TextBuffer.CurrentSnapshot.GetText();
if (_ideScope.FileSystem.File.Exists(filePath)) return _ideScope.FileSystem.File.ReadAllText(filePath);
var fileAdded = _projectScope.FilesAdded.TryGetValue(filePath, out var fileContent);
fileAdded.Should().BeTrue($"file '{filePath}' should have been created");
return fileContent;
}
private class StepDefinitionJumpListData
{
public string StepDefinition { get; set; }
public string StepType { get; set; }
public string HookType { get; set; }
public string Hook { get; set; }
public string HookScope { get; set; }
}
private class StepDefinitionSnippetData
{
public string Type { get; set; }
public string Regex { get; set; }
public string Expression { get; set; }
public string Method { get; set; }
}
}