-
Notifications
You must be signed in to change notification settings - Fork 323
Expand file tree
/
Copy pathHistoryTest.cs
More file actions
1216 lines (1066 loc) · 52.4 KB
/
HistoryTest.cs
File metadata and controls
1216 lines (1066 loc) · 52.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
994
995
996
997
998
999
1000
using System;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Reflection;
using Microsoft.PowerShell;
using Xunit;
namespace Test
{
public partial class ReadLine
{
private void SetHistory(params string[] historyItems)
{
PSConsoleReadLine.ClearHistory();
foreach (var item in historyItems)
{
PSConsoleReadLine.AddToHistory(item);
}
}
[SkippableFact]
public void History()
{
TestSetup(KeyMode.Cmd);
// No history
SetHistory();
Test("", Keys(_.UpArrow, _.DownArrow));
SetHistory("dir c*", "ps p*");
Test("dir c*", Keys(_.UpArrow, _.UpArrow));
Test("dir c*", Keys(_.UpArrow, _.UpArrow, _.DownArrow));
}
[SkippableFact]
public void ParallelHistorySaving()
{
TestSetup(KeyMode.Cmd);
string historySavingFile = Path.GetTempFileName();
var options = new SetPSReadLineOption {
HistorySaveStyle = HistorySaveStyle.SaveIncrementally,
MaximumHistoryCount = 3,
};
typeof(SetPSReadLineOption)
.GetField("_historySavePath", BindingFlags.Instance | BindingFlags.NonPublic)
.SetValue(options, historySavingFile);
PSConsoleReadLine.SetOptions(options);
// Set the initial history items.
string[] initialHistoryItems = new[] { "gcm help", "dir ~" };
SetHistory(initialHistoryItems);
// The initial history items should be saved to file.
string[] text = File.ReadAllLines(historySavingFile);
Assert.Equal(initialHistoryItems.Length, text.Length);
for (int i = 0; i < text.Length; i++)
{
Assert.Equal(initialHistoryItems[i], text[i]);
}
// Add another line to the file to mimic the new history saving from a different session.
using (var file = File.AppendText(historySavingFile))
{
file.WriteLine("cd Downloads");
}
PSConsoleReadLine.AddToHistory("cd Documents");
string[] expectedSavedLines = new[] { "gcm help", "dir ~", "cd Downloads", "cd Documents" };
text = File.ReadAllLines(historySavingFile);
Assert.Equal(expectedSavedLines.Length, text.Length);
for (int i = 0; i < text.Length; i++)
{
Assert.Equal(expectedSavedLines[i], text[i]);
}
string[] expectedHistoryItems = new[] { "dir ~", "cd Documents", "cd Downloads" };
var historyItems = PSConsoleReadLine.GetHistoryItems();
Assert.Equal(expectedHistoryItems.Length, historyItems.Length);
for (int i = 0; i < historyItems.Length; i++)
{
Assert.Equal(expectedHistoryItems[i], historyItems[i].CommandLine);
}
}
[SkippableFact]
public void SensitiveHistoryDefaultBehavior_One()
{
TestSetup(KeyMode.Cmd);
// No history
SetHistory();
Test("", Keys(_.UpArrow, _.DownArrow));
var options = PSConsoleReadLine.GetOptions();
var oldHistoryFilePath = options.HistorySavePath;
var oldHistorySaveStyle = options.HistorySaveStyle;
// AddToHistoryHandler should be set to the default handler.
Assert.Same(PSConsoleReadLineOptions.DefaultAddToHistoryHandler, options.AddToHistoryHandler);
var newHistoryFilePath = Path.GetTempFileName();
var newHistorySaveStyle = HistorySaveStyle.SaveIncrementally;
string[] expectedHistoryItems = new[] {
"gcm c*",
"ConvertTo-SecureString -AsPlainText -String abc -Force",
"dir p*",
"Publish-Module -NuGetApiKey abc",
"ps c*",
"mycommand -password abc",
"echo foo",
"cmd1 /token abc",
"echo bar",
"cmd2 --apikey abc",
"echo zoo",
"pki secret",
"gcm p*"
};
string[] expectedSavedItems = new[] {
"gcm c*",
"dir p*",
"ps c*",
"echo foo",
"echo bar",
"echo zoo",
"gcm p*"
};
try
{
options.HistorySavePath = newHistoryFilePath;
options.HistorySaveStyle = newHistorySaveStyle;
SetHistory(expectedHistoryItems);
// Sensitive input history should be kept in the internal history queue.
var historyItems = PSConsoleReadLine.GetHistoryItems();
Assert.Equal(expectedHistoryItems.Length, historyItems.Length);
for (int i = 0; i < expectedHistoryItems.Length; i++)
{
Assert.Equal(expectedHistoryItems[i], historyItems[i].CommandLine);
}
// Sensitive input history should NOT be saved to the history file.
string[] text = File.ReadAllLines(newHistoryFilePath);
Assert.Equal(expectedSavedItems.Length, text.Length);
for (int i = 0; i < text.Length; i++)
{
Assert.Equal(expectedSavedItems[i], text[i]);
}
}
finally
{
options.HistorySavePath = oldHistoryFilePath;
options.HistorySaveStyle = oldHistorySaveStyle;
File.Delete(newHistoryFilePath);
}
}
[SkippableFact]
public void SensitiveHistoryDefaultBehavior_Two()
{
TestSetup(KeyMode.Cmd);
// Clear history
SetHistory();
var options = PSConsoleReadLine.GetOptions();
var oldHistoryFilePath = options.HistorySavePath;
var oldHistorySaveStyle = options.HistorySaveStyle;
// AddToHistoryHandler should be set to the default handler.
Assert.Same(PSConsoleReadLineOptions.DefaultAddToHistoryHandler, options.AddToHistoryHandler);
var newHistoryFilePath = Path.GetTempFileName();
var newHistorySaveStyle = HistorySaveStyle.SaveIncrementally;
string[] expectedHistoryItems = new[] {
"$token = 'abcd'", // Assign expr-value to sensitive variable. Not saved to file.
"Set-Secret abc $mySecret", // 'Set-Secret' will not be save to file.
"ConvertTo-SecureString stringValue -AsPlainText", // '-AsPlainText' is an alert. Not saved to file.
"Get-Secret PSGalleryApiKey -AsPlainText", // For eligible secret-mgmt command, the whole command is skipped, so '-AsPlainText' here is OK.
"$token = Get-Secret -Name github-token -Vault MySecret",
"[MyType]::CallRestAPI($token, $url, $args)",
"$template -f $token",
"Invoke-RestCall $url -UseDefaultToken",
"Publish-Module -NuGetApiKey $apikey",
"Publish-Module -NuGetApiKey (Get-Secret PSGalleryApiKey -AsPlainText)",
"Publish-Module -NuGetApiKey (Get-NewSecret -Name apikey)", // 'Get-NewSecret' is not in our allow-list. Not saved to file.
"Send-HeartBeat -UseDefaultToken",
"Send-HeartBeat -password $pass -SavePassword",
"Invoke-WebRequest -Token xxx", // Expr-value as argument to '-Token'. Not saved to file.
"Invoke-WebRequest -Token (2+2)", // Expr-value as argument to '-Token'. Not saved to file.
"Get-SecretInfo -Name mytoken; Get-SecretVault; Register-SecretVault; Remove-Secret apikey",
"Get-SecretInfo -Name mytoken; Get-SecretVault; Register-SecretVault; Remove-Secret apikey; Set-Secret", // 'Set-Secret' Not saved to file.
"Set-SecretInfo -Name apikey; Set-SecretVaultDefault; Test-SecretVault; Unlock-SecretVault -password $pwd; Unregister-SecretVault -SecretVault vaultInfo",
"Get-ResultFromTwo -Secret1 (Get-Secret -Name blah -AsPlainText) -Secret2 $secret2",
"Get-ResultFromTwo -Secret1 (Get-Secret -Name blah -AsPlainText) -Secret2 sdv87ysdfayf798hfasd8f7ha", // '-Secret2' has expr-value argument. Not saved to file.
"$environment -brand $brand -userBitWardenEmail $bwuser -userBitWardenPassword $bwpass", // '-userBitWardenPassword' matches sensitive pattern and it has parsing error. Not save to file.
"(Import-Clixml \"${Env:HOME}\\credential.clixml\").GetNetworkCredential().Password | Set-Clipboard", // 'Password' is a property not in assignment.
"$a.Password = 'abcd'", // setting the 'Password' property with string value. Not saved to file.
"$a.Password.Value = 'abcd'", // indirectly setting the 'Password' property with string value. Not saved to file.
"$a.Secret = Get-Secret -Name github-token -Vault MySecret",
"$a.Secret = $secret",
"$a.Password = 'ab' + 'cd'", // setting the 'Password' property with string values. Not saved to file.
"$a.Password.Secret | Set-Value",
"Write-Host $a.Password.Secret",
"($a.Password, $b) = ('aa', 'bb')", // setting the 'Password' property with string value. Not saved to file.
"kubectl get secrets",
"kubectl get secret db-user-pass -o jsonpath='{.data.password}' | base64 --decode",
"kubectl describe secret db-user-pass",
"(Get-AzAccessToken -ResourceUrl 'https://abc.com').Token",
"$token = (Get-AzAccessToken -ResourceUrl 'abc').Token",
"az account get-access-token --resource=https://abc.com --query accessToken --output tsv",
"curl -X GET --header \"Authorization: Bearer $token\" https://abc.com",
"$env:PGPASS = gcloud auth print-access-token",
};
string[] expectedSavedItems = new[] {
"Get-Secret PSGalleryApiKey -AsPlainText",
"$token = Get-Secret -Name github-token -Vault MySecret",
"[MyType]::CallRestAPI($token, $url, $args)",
"$template -f $token",
"Invoke-RestCall $url -UseDefaultToken",
"Publish-Module -NuGetApiKey $apikey",
"Publish-Module -NuGetApiKey (Get-Secret PSGalleryApiKey -AsPlainText)",
"Send-HeartBeat -UseDefaultToken",
"Send-HeartBeat -password $pass -SavePassword",
"Get-SecretInfo -Name mytoken; Get-SecretVault; Register-SecretVault; Remove-Secret apikey",
"Set-SecretInfo -Name apikey; Set-SecretVaultDefault; Test-SecretVault; Unlock-SecretVault -password $pwd; Unregister-SecretVault -SecretVault vaultInfo",
"Get-ResultFromTwo -Secret1 (Get-Secret -Name blah -AsPlainText) -Secret2 $secret2",
"(Import-Clixml \"${Env:HOME}\\credential.clixml\").GetNetworkCredential().Password | Set-Clipboard",
"$a.Secret = Get-Secret -Name github-token -Vault MySecret",
"$a.Secret = $secret",
"$a.Password.Secret | Set-Value",
"Write-Host $a.Password.Secret",
"kubectl get secrets",
"kubectl get secret db-user-pass -o jsonpath='{.data.password}' | base64 --decode",
"kubectl describe secret db-user-pass",
"(Get-AzAccessToken -ResourceUrl 'https://abc.com').Token",
"$token = (Get-AzAccessToken -ResourceUrl 'abc').Token",
"az account get-access-token --resource=https://abc.com --query accessToken --output tsv",
"curl -X GET --header \"Authorization: Bearer $token\" https://abc.com",
"$env:PGPASS = gcloud auth print-access-token",
};
try
{
options.HistorySavePath = newHistoryFilePath;
options.HistorySaveStyle = newHistorySaveStyle;
SetHistory(expectedHistoryItems);
// Sensitive input history should be kept in the internal history queue.
var historyItems = PSConsoleReadLine.GetHistoryItems();
Assert.Equal(expectedHistoryItems.Length, historyItems.Length);
for (int i = 0; i < expectedHistoryItems.Length; i++)
{
Assert.Equal(expectedHistoryItems[i], historyItems[i].CommandLine);
}
// Sensitive input history should NOT be saved to the history file.
string[] text = File.ReadAllLines(newHistoryFilePath);
Assert.Equal(expectedSavedItems.Length, text.Length);
for (int i = 0; i < text.Length; i++)
{
Assert.Equal(expectedSavedItems[i], text[i]);
}
}
finally
{
options.HistorySavePath = oldHistoryFilePath;
options.HistorySaveStyle = oldHistorySaveStyle;
File.Delete(newHistoryFilePath);
}
}
[SkippableFact]
public void SensitiveHistoryOptionalBehavior()
{
TestSetup(KeyMode.Cmd);
// No history
SetHistory();
Test("", Keys(_.UpArrow, _.DownArrow));
var options = PSConsoleReadLine.GetOptions();
var oldHistoryFilePath = options.HistorySavePath;
var oldHistorySaveStyle = options.HistorySaveStyle;
// AddToHistoryHandler should be set to the default handler.
Assert.Same(PSConsoleReadLineOptions.DefaultAddToHistoryHandler, options.AddToHistoryHandler);
var newHistoryFilePath = Path.GetTempFileName();
var newHistorySaveStyle = HistorySaveStyle.SaveIncrementally;
Func<string, object> newAddToHistoryHandler_ReturnBool = s => s.Contains("gal");
Func<string, object> newAddToHistoryHandler_ReturnEnum =
s => s.Contains("gal")
? AddToHistoryOption.MemoryOnly
: s.Contains("gmo")
? AddToHistoryOption.SkipAdding
: AddToHistoryOption.MemoryAndFile;
Func<string, object> newAddToHistoryHandler_ReturnOther = s => "string value";
string[] commandInputs = new[] {
"gmo p*",
"gcm c*",
"gal dir",
"ConvertTo-SecureString -AsPlainText -String abc -Force"
};
string[] expectedQueuedItems = new[] {
"gcm c*",
"gal dir",
"ConvertTo-SecureString -AsPlainText -String abc -Force"
};
string[] expectedSavedItems = new[] {
"gcm c*",
"ConvertTo-SecureString -AsPlainText -String abc -Force"
};
try
{
options.HistorySavePath = newHistoryFilePath;
options.HistorySaveStyle = newHistorySaveStyle;
//
// Set null to the handler means we don't do the check.
//
options.AddToHistoryHandler = null;
SetHistory(commandInputs);
// All commands should be kept in the internal history queue.
var historyItems = PSConsoleReadLine.GetHistoryItems();
Assert.Equal(commandInputs.Length, historyItems.Length);
for (int i = 0; i < commandInputs.Length; i++)
{
Assert.Equal(commandInputs[i], historyItems[i].CommandLine);
}
// All commands are saved to the history file when 'ScrubSensitiveHistory' is set to 'false'.
string[] text = File.ReadAllLines(newHistoryFilePath);
Assert.Equal(commandInputs.Length, text.Length);
for (int i = 0; i < text.Length; i++)
{
Assert.Equal(commandInputs[i], text[i]);
}
//
// Use a handler that return boolean value.
// true: Add to memory and file
// false: Skip adding to history
//
options.AddToHistoryHandler = newAddToHistoryHandler_ReturnBool;
// Clear the history file.
File.WriteAllText(newHistoryFilePath, string.Empty);
SetHistory(commandInputs);
historyItems = PSConsoleReadLine.GetHistoryItems();
Assert.Single(historyItems);
Assert.Equal("gal dir", historyItems[0].CommandLine);
text = File.ReadAllLines(newHistoryFilePath);
Assert.Single(text);
Assert.Equal("gal dir", text[0]);
//
// Use a handler that return the expected enum type.
//
options.AddToHistoryHandler = newAddToHistoryHandler_ReturnEnum;
File.WriteAllText(newHistoryFilePath, string.Empty);
SetHistory(commandInputs);
historyItems = PSConsoleReadLine.GetHistoryItems();
Assert.Equal(expectedQueuedItems.Length, historyItems.Length);
for (int i = 0; i < expectedQueuedItems.Length; i++)
{
Assert.Equal(expectedQueuedItems[i], historyItems[i].CommandLine);
}
text = File.ReadAllLines(newHistoryFilePath);
Assert.Equal(expectedSavedItems.Length, text.Length);
for (int i = 0; i < text.Length; i++)
{
Assert.Equal(expectedSavedItems[i], text[i]);
}
//
// Use a handler that return unexpected value.
// - same behavior as setting the handler to null.
//
options.AddToHistoryHandler = newAddToHistoryHandler_ReturnOther;
File.WriteAllText(newHistoryFilePath, string.Empty);
SetHistory(commandInputs);
historyItems = PSConsoleReadLine.GetHistoryItems();
Assert.Equal(commandInputs.Length, historyItems.Length);
for (int i = 0; i < commandInputs.Length; i++)
{
Assert.Equal(commandInputs[i], historyItems[i].CommandLine);
}
// All commands are saved to the history file when 'ScrubSensitiveHistory' is set to 'false'.
text = File.ReadAllLines(newHistoryFilePath);
Assert.Equal(commandInputs.Length, text.Length);
for (int i = 0; i < text.Length; i++)
{
Assert.Equal(commandInputs[i], text[i]);
}
}
finally
{
options.HistorySavePath = oldHistoryFilePath;
options.HistorySaveStyle = oldHistorySaveStyle;
options.AddToHistoryHandler = PSConsoleReadLineOptions.DefaultAddToHistoryHandler;
File.Delete(newHistoryFilePath);
}
}
[SkippableFact]
public void SensitiveHistoryOptionalBehaviorWithScriptBlock()
{
TestSetup(KeyMode.Cmd);
// No history
SetHistory();
Test("", Keys(_.UpArrow, _.DownArrow));
var options = PSConsoleReadLine.GetOptions();
var oldHistoryFilePath = options.HistorySavePath;
var oldHistorySaveStyle = options.HistorySaveStyle;
// AddToHistoryHandler should be set to the default handler.
Assert.Same(PSConsoleReadLineOptions.DefaultAddToHistoryHandler, options.AddToHistoryHandler);
var newHistoryFilePath = Path.GetTempFileName();
var newHistorySaveStyle = HistorySaveStyle.SaveIncrementally;
Func<string, object> newAddToHistoryHandler_ReturnBool = LanguagePrimitives.ConvertTo<Func<string, object>>(
ScriptBlock.Create(@"
param([string]$line)
$line.Contains('gal')"));
Func<string, object> newAddToHistoryHandler_ReturnEnum = LanguagePrimitives.ConvertTo<Func<string, object>>(
ScriptBlock.Create(@"
param([string]$line)
if ($line.Contains('gal')) {
[psobject]::AsPSObject([Microsoft.PowerShell.AddToHistoryOption]::MemoryOnly)
} elseif ($line.Contains('gmo')) {
'SkipAdding'
} else {
[Microsoft.PowerShell.AddToHistoryOption]::MemoryAndFile
}"));
Func<string, object> newAddToHistoryHandler_ReturnOther = LanguagePrimitives.ConvertTo<Func<string, object>>(
ScriptBlock.Create(@"
param([string]$line)
'string value'"));
string[] commandInputs = new[] {
"gmo p*",
"gcm c*",
"gal dir",
"ConvertTo-SecureString -AsPlainText -String abc -Force"
};
string[] expectedQueuedItems = new[] {
"gcm c*",
"gal dir",
"ConvertTo-SecureString -AsPlainText -String abc -Force"
};
string[] expectedSavedItems = new[] {
"gcm c*",
"ConvertTo-SecureString -AsPlainText -String abc -Force"
};
try
{
options.HistorySavePath = newHistoryFilePath;
options.HistorySaveStyle = newHistorySaveStyle;
//
// Set null to the handler means we don't do the check.
//
options.AddToHistoryHandler = null;
SetHistory(commandInputs);
// All commands should be kept in the internal history queue.
var historyItems = PSConsoleReadLine.GetHistoryItems();
Assert.Equal(commandInputs.Length, historyItems.Length);
for (int i = 0; i < commandInputs.Length; i++)
{
Assert.Equal(commandInputs[i], historyItems[i].CommandLine);
}
// All commands are saved to the history file when 'ScrubSensitiveHistory' is set to 'false'.
string[] text = File.ReadAllLines(newHistoryFilePath);
Assert.Equal(commandInputs.Length, text.Length);
for (int i = 0; i < text.Length; i++)
{
Assert.Equal(commandInputs[i], text[i]);
}
//
// Use a handler that return boolean value.
// true: Add to memory and file
// false: Skip adding to history
//
options.AddToHistoryHandler = newAddToHistoryHandler_ReturnBool;
// Clear the history file.
File.WriteAllText(newHistoryFilePath, string.Empty);
SetHistory(commandInputs);
historyItems = PSConsoleReadLine.GetHistoryItems();
Assert.Single(historyItems);
Assert.Equal("gal dir", historyItems[0].CommandLine);
text = File.ReadAllLines(newHistoryFilePath);
Assert.Single(text);
Assert.Equal("gal dir", text[0]);
//
// Use a handler that return the expected enum type.
//
options.AddToHistoryHandler = newAddToHistoryHandler_ReturnEnum;
File.WriteAllText(newHistoryFilePath, string.Empty);
SetHistory(commandInputs);
historyItems = PSConsoleReadLine.GetHistoryItems();
Assert.Equal(expectedQueuedItems.Length, historyItems.Length);
for (int i = 0; i < expectedQueuedItems.Length; i++)
{
Assert.Equal(expectedQueuedItems[i], historyItems[i].CommandLine);
}
text = File.ReadAllLines(newHistoryFilePath);
Assert.Equal(expectedSavedItems.Length, text.Length);
for (int i = 0; i < text.Length; i++)
{
Assert.Equal(expectedSavedItems[i], text[i]);
}
//
// Use a handler that return unexpected value.
// - same behavior as setting the handler to null.
//
options.AddToHistoryHandler = newAddToHistoryHandler_ReturnOther;
File.WriteAllText(newHistoryFilePath, string.Empty);
SetHistory(commandInputs);
historyItems = PSConsoleReadLine.GetHistoryItems();
Assert.Equal(commandInputs.Length, historyItems.Length);
for (int i = 0; i < commandInputs.Length; i++)
{
Assert.Equal(commandInputs[i], historyItems[i].CommandLine);
}
// All commands are saved to the history file when 'ScrubSensitiveHistory' is set to 'false'.
text = File.ReadAllLines(newHistoryFilePath);
Assert.Equal(commandInputs.Length, text.Length);
for (int i = 0; i < text.Length; i++)
{
Assert.Equal(commandInputs[i], text[i]);
}
}
finally
{
options.HistorySavePath = oldHistoryFilePath;
options.HistorySaveStyle = oldHistorySaveStyle;
options.AddToHistoryHandler = PSConsoleReadLineOptions.DefaultAddToHistoryHandler;
File.Delete(newHistoryFilePath);
}
}
[SkippableFact]
public void HistoryRecallCurrentLine()
{
TestSetup(KeyMode.Cmd);
// Recall history backward and forward.
SetHistory("echo foo", "echo bar");
Test("ec", Keys(
"ec",
_.UpArrow, CheckThat(() => AssertLineIs("echo bar")),
_.UpArrow, CheckThat(() => AssertLineIs("echo foo")),
_.DownArrow, CheckThat(() => AssertLineIs("echo bar")),
_.DownArrow));
// Verify that the saved current line gets reset when the line gets edited.
// Recall history, then edit the line, and recall again.
SetHistory("echo foo", "echo bar");
Test("get", Keys(
"ec", _.UpArrow,
_.DownArrow, CheckThat(() => AssertLineIs("ec")),
_.Escape, "get", _.UpArrow, _.DownArrow));
// Recall history, then edit the line, and recall again.
SetHistory("echo foo", "echo bar");
Test("ge", Keys(
"ec", _.UpArrow,
_.DownArrow, CheckThat(() => AssertLineIs("ec")),
_.Backspace, _.Backspace, "ge", CheckThat(() => AssertLineIs("ge")),
_.UpArrow, _.DownArrow));
// Recall history, then edit the line, and recall again.
SetHistory("echo foo", "echo bar");
Test("", Keys(
"ec", _.UpArrow,
_.DownArrow, CheckThat(() => AssertLineIs("ec")),
"h", CheckThat(() => AssertLineIs("ech")),
_.UpArrow, CheckThat(() => AssertLineIs("echo bar")),
_.DownArrow, CheckThat(() => AssertLineIs("ech")),
_.Escape));
}
[SkippableFact]
public void HistorySearchCurrentLine()
{
TestSetup(KeyMode.Cmd,
new KeyHandler("UpArrow", PSConsoleReadLine.HistorySearchBackward),
new KeyHandler("DownArrow", PSConsoleReadLine.HistorySearchForward));
// Search history backward and forward.
SetHistory("echo foo", "echo bar");
Test("ec", Keys(
"ec",
_.UpArrow, CheckThat(() => AssertLineIs("echo bar")),
_.UpArrow, CheckThat(() => AssertLineIs("echo foo")),
_.DownArrow, CheckThat(() => AssertLineIs("echo bar")),
_.DownArrow));
// Verify that the saved current line gets reset when the line gets edited.
// Search history, then edit the line, and search again.
SetHistory("echo foo", "echo bar");
Test("echo ", Keys(
"ec", _.UpArrow,
_.DownArrow, CheckThat(() => AssertLineIs("ec")),
_.Escape, "echo ",
_.UpArrow, CheckThat(() => AssertLineIs("echo bar")),
_.DownArrow));
// Search history, then edit the line, and search again.
SetHistory("echo foo", "echo bar");
Test("echo", Keys(
"ec", _.UpArrow, _.DownArrow,
"ho", CheckThat(() => AssertLineIs("echo")),
_.UpArrow, _.DownArrow));
// Search history, then edit the line, and search again.
SetHistory("echo foo", "echo bar");
Test("e", Keys(
"ec", _.UpArrow, _.DownArrow,
_.Backspace, CheckThat(() => AssertLineIs("e")),
_.UpArrow, _.DownArrow));
// Search history, then edit the line, and search again.
SetHistory("echo foo", "echo bar");
Test("", Keys(
"ec", _.UpArrow, _.DownArrow, "ho f",
_.UpArrow, CheckThat(() => AssertLineIs("echo foo")),
_.DownArrow, CheckThat(() => AssertLineIs("echo f")),
_.Escape));
}
[SkippableFact]
public void HistorySavedCurrentLine()
{
TestSetup(KeyMode.Cmd,
new KeyHandler("F3", PSConsoleReadLine.BeginningOfHistory),
new KeyHandler("Shift+F3", PSConsoleReadLine.EndOfHistory));
// Mix different history commands to verify that the saved current line and
// the history index stay the same while in a series of history commands.
SetHistory("echo foo", "echo bar");
Test("ec", Keys(
"ec",
_.UpArrow, CheckThat(() => AssertLineIs("echo bar")),
_.F3, CheckThat(() => AssertLineIs("echo foo")),
_.DownArrow, CheckThat(() => AssertLineIs("echo bar")),
_.DownArrow));
SetHistory("echo foo", "get zoo", "echo bar");
Test("ec", Keys(
"ec",
_.UpArrow, CheckThat(() => AssertLineIs("echo bar")),
_.F3, CheckThat(() => AssertLineIs("echo foo")),
_.Shift_F3));
SetHistory("echo foo", "get zoo", "echo bar");
Test("e", Keys(
"e",
_.UpArrow, CheckThat(() => AssertLineIs("echo bar")),
_.UpArrow, CheckThat(() => AssertLineIs("get zoo")),
_.Shift_F3));
SetHistory("echo foo", "get zoo", "echo bar");
Test("ech", Keys(
"ech",
_.F8, CheckThat(() => AssertLineIs("echo bar")),
_.F3, CheckThat(() => AssertLineIs("echo foo")),
_.DownArrow, CheckThat(() => AssertLineIs("get zoo")),
_.DownArrow, CheckThat(() => AssertLineIs("echo bar")),
_.DownArrow));
SetHistory("echo foo", "get zoo", "echo bar");
Test("ech", Keys(
"ech",
_.F8, CheckThat(() => AssertLineIs("echo bar")),
_.F8, CheckThat(() => AssertLineIs("echo foo")),
_.Shift_F3));
SetHistory("echo foo", "get bar", "echo f");
Test("ec", Keys(
"ec",
_.UpArrow, CheckThat(() => AssertLineIs("echo f")),
_.F8, CheckThat(() => AssertLineIs("echo foo")),
_.Shift_F8, CheckThat(() => AssertLineIs("echo f")),
_.DownArrow));
SetHistory("echo foo", "get bar", "echo f");
Test("ec", Keys(
"ec", _.UpArrow, _.F8,
_.DownArrow, CheckThat(() => AssertLineIs("get bar")),
_.DownArrow, CheckThat(() => AssertLineIs("echo f")),
_.Shift_F3));
SetHistory("echo kv", "get bar", "echo f");
Test("e", Keys(
"e",
_.UpArrow, CheckThat(() => AssertLineIs("echo f")),
_.Ctrl_r, "v", _.Escape,
CheckThat(() => AssertLineIs("echo kv")),
_.Ctrl_s, "f", _.Escape,
CheckThat(() => AssertLineIs("echo f")),
_.UpArrow, CheckThat(() => AssertLineIs("get bar")),
_.DownArrow, _.DownArrow));
}
[SkippableFact]
public void SearchHistory()
{
TestSetup(KeyMode.Cmd,
new KeyHandler("UpArrow", PSConsoleReadLine.HistorySearchBackward),
new KeyHandler("DownArrow", PSConsoleReadLine.HistorySearchForward));
// No history
SetHistory();
Test("", Keys(_.UpArrow, _.DownArrow));
// Clear history in case the above added some history (but it shouldn't)
SetHistory();
Test(" ", Keys(' ', _.UpArrow, _.DownArrow));
PSConsoleReadLine.SetOptions(new SetPSReadLineOption {HistorySearchCursorMovesToEnd = false});
var emphasisColors = Tuple.Create(PSConsoleReadLineOptions.DefaultEmphasisColor, _console.BackgroundColor);
SetHistory("dosomething", "ps p*", "dir", "echo zzz");
Test("dosomething", Keys(
"d",
_.UpArrow, CheckThat(() => {
AssertScreenIs(1,
emphasisColors, 'd',
TokenClassification.Command, "ir");
AssertCursorLeftIs(1);
}),
_.UpArrow, CheckThat(() => {
AssertScreenIs(1,
emphasisColors, 'd',
TokenClassification.Command, "osomething");
AssertCursorLeftIs(1);
})));
PSConsoleReadLine.SetOptions(new SetPSReadLineOption {HistorySearchCursorMovesToEnd = true});
SetHistory("dosomething", "ps p*", "dir", "echo zzz");
Test("dosomething", Keys(
"d",
_.UpArrow, CheckThat(() => {
AssertScreenIs(1,
emphasisColors, 'd',
TokenClassification.Command, "ir");
AssertCursorLeftIs(3);
}),
_.UpArrow, CheckThat(() => {
AssertScreenIs(1,
emphasisColors, 'd',
TokenClassification.Command, "osomething");
AssertCursorLeftIs(11);
}),
_.DownArrow, CheckThat(() => {
AssertScreenIs(1,
emphasisColors, 'd',
TokenClassification.Command, "ir");
AssertCursorLeftIs(3);
}),
_.UpArrow, CheckThat(() =>
{
AssertScreenIs(1,
emphasisColors, 'd',
TokenClassification.Command, "osomething");
AssertCursorLeftIs(11);
})));
}
[SkippableFact]
public void HistorySearchCursorMovesToEnd()
{
TestSetup(KeyMode.Cmd,
new KeyHandler("UpArrow", PSConsoleReadLine.HistorySearchBackward),
new KeyHandler("DownArrow", PSConsoleReadLine.HistorySearchForward));
PSConsoleReadLine.SetOptions(new SetPSReadLineOption {HistorySearchCursorMovesToEnd = true});
var emphasisColors = Tuple.Create(PSConsoleReadLineOptions.DefaultEmphasisColor, _console.BackgroundColor);
SetHistory("dosomething", "ps p*", "dir", "echo zzz");
Test("dosomething", Keys(
"d",
_.UpArrow, CheckThat(() => {
AssertScreenIs(1,
emphasisColors, 'd',
TokenClassification.Command, "ir");
AssertCursorLeftIs(3);
}),
_.UpArrow, CheckThat(() => {
AssertScreenIs(1,
emphasisColors, 'd',
TokenClassification.Command, "osomething");
AssertCursorLeftIs(11);
}),
_.DownArrow, CheckThat(() => {
AssertScreenIs(1,
emphasisColors, 'd',
TokenClassification.Command, "ir");
AssertCursorLeftIs(3);
}),
_.UpArrow, CheckThat(() =>
{
AssertScreenIs(1,
emphasisColors, 'd',
TokenClassification.Command, "osomething");
AssertCursorLeftIs(11);
})));
}
[SkippableFact]
public void BeginningOfHistory()
{
Skip.IfNot(KeyboardHasLessThan);
TestSetup(KeyMode.Emacs);
SetHistory("echo first", "echo second", "echo third");
Test("echo first", Keys(_.Alt_Less));
SetHistory("echo first", "echo second", "echo third");
Test("echo second", Keys(_.Alt_Less, _.DownArrow));
}
[SkippableFact]
public void EndOfHistory()
{
Skip.IfNot(KeyboardHasGreaterThan);
TestSetup(KeyMode.Emacs);
SetHistory("echo first", "echo second", "echo third");
Test("", Keys(_.UpArrow, _.Alt_Greater));
// Make sure end of history restores the "current" line if
// there was anything entered before going through history
Test("abc", Keys("abc", _.UpArrow, _.Alt_Greater));
// Make sure we don't recall the previous "current" line
// after we accepted it.
Test("", Keys(_.Alt_Greater));
}
[SkippableFact]
public void InteractiveHistorySearch()
{
TestSetup(KeyMode.Emacs);
SetHistory("echo aaa");
Test("echo aaa", Keys(_.Ctrl_r, 'a'));
var emphasisColors = Tuple.Create(PSConsoleReadLineOptions.DefaultEmphasisColor, _console.BackgroundColor);
var statusColors = Tuple.Create(_console.ForegroundColor, _console.BackgroundColor);
// Test entering multiple characters and the line is updated with new matches
SetHistory("zz1", "echo abc", "zz2", "echo abb", "zz3", "echo aaa", "zz4");
Test("echo abc", Keys(_.Ctrl_r,
'a',
CheckThat(() => AssertScreenIs(2,
TokenClassification.Command, "echo",
TokenClassification.None, " ",
emphasisColors, 'a',
TokenClassification.None, "aa",
NextLine,
statusColors, "bck-i-search: a_")),
'b', CheckThat(() => AssertScreenIs(2,
TokenClassification.Command, "echo",
TokenClassification.None, " ",
emphasisColors, "ab",
TokenClassification.None, 'b',
NextLine,
statusColors, "bck-i-search: ab_")),
'c', CheckThat(() => AssertScreenIs(2,
TokenClassification.Command, "echo",
TokenClassification.None, " ",
emphasisColors, "abc",
NextLine,
statusColors, "bck-i-search: abc_"))));
// Test repeated Ctrl+r goes back through multiple matches
SetHistory("zz1", "echo abc", "zz2", "echo abb", "zz3", "echo aaa", "zz4");
Test("echo abc", Keys(_.Ctrl_r,
'a',
CheckThat(() => AssertScreenIs(2,
TokenClassification.Command, "echo",
TokenClassification.None, " ",
emphasisColors, 'a',
TokenClassification.None, "aa",
NextLine,
statusColors, "bck-i-search: a_")),
_.Ctrl_r, CheckThat(() => AssertScreenIs(2,
TokenClassification.Command, "echo",
TokenClassification.None, " ",
emphasisColors, 'a',
TokenClassification.None, "bb",
NextLine,
statusColors, "bck-i-search: a_")),
_.Ctrl_r, CheckThat(() => AssertScreenIs(2,
TokenClassification.Command, "echo",
TokenClassification.None, " ",
emphasisColors, 'a',
TokenClassification.None, "bc",
NextLine,
statusColors, "bck-i-search: a_"))));
// Test that the current match doesn't change when typing
// additional characters, only emphasis should change.
SetHistory("zz1", "echo abzz", "echo abc", "zz2");
Test("echo abc", Keys(_.Ctrl_r,
'a',
CheckThat(() => AssertScreenIs(2,
TokenClassification.Command, "echo",
TokenClassification.None, " ",
emphasisColors, 'a',
TokenClassification.None, "bc",
NextLine,
statusColors, "bck-i-search: a_")),
'b',
CheckThat(() => AssertScreenIs(2,
TokenClassification.Command, "echo",
TokenClassification.None, " ",
emphasisColors, "ab",
TokenClassification.None, 'c',
NextLine,
statusColors, "bck-i-search: ab_"))));
// Test that abort restores line state before Ctrl+r
SetHistory("zz1", "echo abzz", "echo abc", "zz2");
Test("echo zed", Keys("echo zed", _.Ctrl_r,
'a',
CheckThat(() => AssertScreenIs(2,
TokenClassification.Command, "echo",
TokenClassification.None, " ",
emphasisColors, 'a',
TokenClassification.None, "bc",
NextLine,
statusColors, "bck-i-search: a_")),
_.Ctrl_g,
CheckThat(() => AssertScreenIs(2,
TokenClassification.Command, "echo",
TokenClassification.None, " ",
TokenClassification.None, "zed",
NextLine))));
// Test that a random function terminates the search and has an
// effect on the line found in history
SetHistory("zz1", "echo abzz", "echo abc", "zz2");
Test("echo zed", Keys(_.Ctrl_r,
'a',
CheckThat(() => AssertScreenIs(2,
TokenClassification.Command, "echo",
TokenClassification.None, " ",
emphasisColors, 'a',
TokenClassification.None, "bc",
NextLine,
statusColors, "bck-i-search: a_")),
_.Alt_d, "zed"));
// Test that Escape terminates the search leaving the
// cursor at the point in the match.
SetHistory("zz1", "echo abzz", "echo abc", "zz2");
Test("echo yabc", Keys(_.Ctrl_r,