-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain_test.go
More file actions
2133 lines (1680 loc) · 57.4 KB
/
main_test.go
File metadata and controls
2133 lines (1680 loc) · 57.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
// Copyright (c) 2025 Andre Nogueira
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
// Package main provides comprehensive tests for the crontab guru TUI application.
//
// Test Coverage:
// - Model initialization and state management
// - Keyboard navigation (Tab, Shift+Tab, Enter, Space, Backspace)
// - Cron expression validation (wildcards, ranges, steps, abbreviations)
// - Human-readable description generation
// - Next run time calculation
// - Clipboard operations
// - UI rendering and styling
// - Error handling and recovery
// - Edge cases and boundary conditions
//
// All tests use t.Parallel() for concurrent execution where possible,
// though some tests interact with shared global state (like the program variable).
package main
import (
"os"
"runtime"
"strings"
"testing"
tea "github.com/charmbracelet/bubbletea"
"github.com/cockroachdb/errors"
)
const (
linuxOS = "linux"
)
// assertModelType safely asserts that a tea.Model is a *model.
// This helper function provides type-safe conversion from tea.Model interface
// to the concrete *model type, failing the test if the assertion fails.
func assertModelType(t *testing.T, teaModel tea.Model) *model {
t.Helper()
m, ok := teaModel.(*model)
if !ok {
t.Fatalf("Expected *model, got %T", teaModel)
}
return m
}
// TestInitialModel verifies that the model is initialized correctly with:
// - 5 input fields (minute, hour, day, month, weekday)
// - First input focused
// - Default cron expression "20 4 * * *" (4:20 AM daily)
func TestInitialModel(t *testing.T) {
t.Parallel()
m := initialModel()
if len(m.inputs) != 5 {
t.Errorf("Expected 5 inputs, but got %d", len(m.inputs))
}
if m.inputs[0].Focused() != true {
t.Error("Expected the first input to be focused")
}
initialValues := []string{"20", "4", "*", "*", "*"}
for i, v := range initialValues {
if m.inputs[i].Value() != v {
t.Errorf("Expected input %d to have value %s, but got %s", i, v, m.inputs[i].Value())
}
}
}
// TestUpdateFocus verifies keyboard navigation between input fields:
// - Tab cycles through all 5 fields with wraparound
// - Shift+Tab moves to the previous field
func TestUpdateFocus(t *testing.T) {
t.Parallel()
m := initialModel()
// Test Tab navigation
for i := range 5 {
if m.focusIndex != i%5 {
t.Errorf("Expected focus index to be %d, but got %d", i%5, m.focusIndex)
}
keyMsg := tea.KeyMsg{Type: tea.KeyTab}
newModel, _ := m.Update(keyMsg)
m = assertModelType(t, newModel)
}
// Test Shift+Tab navigation
m = initialModel() // Reset model
keyMsg := tea.KeyMsg{Type: tea.KeyShiftTab}
newModel, _ := m.Update(keyMsg)
m = assertModelType(t, newModel)
if m.focusIndex != 4 {
t.Errorf("Expected focus index to be 4 after Shift+Tab, but got %d", m.focusIndex)
}
}
// TestUpdateCopy verifies that pressing 'y' copies the cron expression
// to the clipboard and displays a success message with a timer to clear it.
// In environments where clipboard is not available, it should show an appropriate message.
func TestUpdateCopy(t *testing.T) {
t.Parallel()
m := initialModel()
keyMsg := tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("y")}
newModel, cmd := m.Update(keyMsg)
m = assertModelType(t, newModel)
// In CI/headless environments, clipboard may not be available
if !clipboardAvailable() {
if m.copyMessage != "Clipboard not available" {
t.Errorf("Expected copy message to be \"Clipboard not available\", but got \"%s\"", m.copyMessage)
}
} else {
// In environments with clipboard support, check for success or failure message
if m.copyMessage != copyMessageText && m.copyMessage != copyFailedText {
t.Errorf("Expected copy message to be \"%s\" or \"%s\", but got \"%s\"",
copyMessageText, copyFailedText, m.copyMessage)
}
}
if cmd == nil {
t.Error("Expected a command to be returned for clearing the message")
}
// Execute the command and check the message
msg := cmd()
if _, ok := msg.(clearCopyMessage); !ok {
t.Errorf("Expected command to return a clearCopyMessage, but got %T", msg)
}
}
// TestUpdateDescriptionErrors verifies error handling for invalid cron expressions.
// Empty values are treated as wildcards (*), so they should produce valid descriptions.
func TestUpdateDescriptionErrors(t *testing.T) {
t.Parallel()
m := initialModel()
// Test with all empty values - should convert to "* * * * *" (every minute)
for i := range m.inputs {
m.inputs[i].SetValue("")
}
m.updateDescription()
// Empty values are treated as *, so we should get a valid description
if m.description == "" {
t.Error("Expected a valid description for '* * * * *', but got empty")
}
if m.err != nil {
t.Errorf("Expected no error for '* * * * *', but got: %v", m.err)
}
// Test invalid cron for ToDescription - single letter that's not valid
m = initialModel() // Reset
m.inputs[0].SetValue("x")
m.updateDescription()
if m.err == nil {
t.Error("Expected an error for invalid cron expression in ToDescription, but got nil")
}
}
// TestUpdateMessages verifies handling of various message types in the Update method,
// including clearCopyMessage, Ctrl+C, '?', Backspace, and WindowSizeMsg.
func TestUpdateMessages(t *testing.T) {
t.Parallel()
m := initialModel()
// Test clearCopyMessage
m.copyMessage = "test"
newModel, _ := m.Update(clearCopyMessage{})
m = assertModelType(t, newModel)
if m.copyMessage != "" {
t.Errorf("Expected copyMessage to be empty, but got: %s", m.copyMessage)
}
// Test Ctrl+C - should trigger quit
keyMsg := tea.KeyMsg{Type: tea.KeyCtrlC}
newModel, _ = m.Update(keyMsg)
m = assertModelType(t, newModel)
// Test '?' key - toggles help display
m.showHelp = false
keyMsg = tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("?")}
newModel, _ = m.Update(keyMsg)
m = assertModelType(t, newModel)
if !m.showHelp {
t.Error("Expected showHelp to be true after '?'")
}
newModel, _ = m.Update(keyMsg) // Press again to toggle off
m = assertModelType(t, newModel)
if m.showHelp {
t.Error("Expected showHelp to be false after second '?'")
}
// Test backspace - should move to previous field when current field is empty
m.focusIndex = 1
m.inputs[1].SetValue("")
keyMsg = tea.KeyMsg{Type: tea.KeyBackspace}
newModel, _ = m.Update(keyMsg)
m = assertModelType(t, newModel)
if m.focusIndex != 0 {
t.Errorf("Expected focus index to be 0 after backspace on empty input, but got %d", m.focusIndex)
}
// Test WindowSizeMsg - should update terminal dimensions
winSizeMsg := tea.WindowSizeMsg{Width: 80, Height: 24}
newModel, _ = m.Update(winSizeMsg)
m = assertModelType(t, newModel)
if m.width != 80 || m.height != 24 {
t.Errorf("Expected width=80, height=24, but got width=%d, height=%d", m.width, m.height)
}
}
// TestUpdateInputs verifies that character input updates the focused input field correctly.
func TestUpdateInputs(t *testing.T) {
t.Parallel()
m := initialModel()
m.focusIndex = 0
// Simulate typing '1'
keyMsg := tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("1")}
newModel, _ := m.Update(keyMsg)
m = assertModelType(t, newModel)
expectedValue := "201"
if m.inputs[0].Value() != expectedValue {
t.Errorf("Expected input 0 to have value \"%s\", but got \"%s\"", expectedValue, m.inputs[0].Value())
}
}
// TestInit verifies that the Init() method returns a valid command
// (the text cursor blink command for the Bubble Tea framework).
func TestInit(t *testing.T) {
t.Parallel()
m := initialModel()
cmd := m.Init()
if cmd == nil {
t.Error("Expected a command from Init(), but got nil")
}
}
// TestUpdateDescriptionParseError verifies that invalid cron values
// (like day 32) are handled gracefully and don't produce a next run time.
func TestUpdateDescriptionParseError(t *testing.T) {
t.Parallel()
m := initialModel()
m.inputs[2].SetValue("32") // Day 32 is invalid
m.updateDescription()
if m.nextRun != "" {
t.Errorf("Expected empty nextRun for invalid cron parse, but got: %s", m.nextRun)
}
}
// TestUpdateDefaultCase verifies that regular character input is properly
// handled and updates the focused input field.
func TestUpdateDefaultCase(t *testing.T) {
t.Parallel()
m := initialModel()
m.focusIndex = 1
m.inputs[0].Blur()
m.inputs[1].Focus()
m.inputs[1].SetValue("1")
keyMsg := tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("a")}
newModel, _ := m.Update(keyMsg)
m = assertModelType(t, newModel)
expectedValue := "1a"
if m.inputs[1].Value() != expectedValue {
t.Errorf("Expected input 1 to have value \"%s\", but got \"%s\"", expectedValue, m.inputs[1].Value())
}
}
// TestView verifies that the View() method renders all UI components correctly,
// including the title, description, inputs, and instructions.
func TestView(t *testing.T) {
t.Parallel()
m := initialModel()
m.width = 80 // Set a fixed width for predictable layout
// Test default view
view := m.View()
if !strings.Contains(view, "crontab guru") {
t.Error("View should contain the title")
}
if !strings.Contains(view, "Press ? for help") {
t.Error("View should contain the default help text")
}
// Test with error
m.err = errors.New("test error")
m.description = ""
view = m.View()
if !strings.Contains(view, "Error: test error") {
t.Error("View should contain the error message")
}
m.err = nil // Reset error
// Test with empty description and no error
m.description = ""
view = m.View()
if !strings.Contains(view, "\n\n") {
t.Error("View should contain a blank line for empty description")
}
// Test with showHelp
m.showHelp = true
view = m.View()
if !strings.Contains(view, "tab/space/enter: next field") {
t.Error("View should contain the detailed help text when showHelp is true")
}
m.showHelp = false // Reset
// Test with copyMessage
m.copyMessage = copyMessageText
view = m.View()
if !strings.Contains(view, copyMessageText) {
t.Error("View should contain the copy message")
}
// Test with no nextRun
m.nextRun = ""
view = m.View()
if !strings.Contains(view, "\n\n") {
t.Error("View should contain a blank line for empty nextRun")
}
}
// TestUpdateCopyMessageCleared verifies that the clearCopyMessage message type
// properly resets the copy message after the timer expires.
func TestUpdateCopyMessageCleared(t *testing.T) {
t.Parallel()
m := initialModel()
m.copyMessage = copyMessageText
// Simulate the clearCopyMessage
newModel, _ := m.Update(clearCopyMessage{})
m = assertModelType(t, newModel)
if m.copyMessage != "" {
t.Errorf("Expected copy message to be cleared, but got \"%s\"", m.copyMessage)
}
}
// TestRun verifies that the run() function can start and stop the application
// correctly when a Quit message is sent. In CI environments without TTY,
// the function should exit gracefully.
func TestRun(t *testing.T) {
t.Parallel()
// Note: This test will exit early in CI environments without TTY
err := run()
if err != nil {
t.Errorf("run() returned an error: %v", err)
}
}
// TestViewWithNegativeFocusIndex verifies that the View() method handles
// edge cases with invalid focus indices without panicking.
func TestViewWithNegativeFocusIndex(t *testing.T) {
t.Parallel()
m := initialModel()
m.width = 80
// Force a negative focus index (simulating edge case)
m.focusIndex = -1
// This should not panic
view := m.View()
if view == "" {
t.Error("View should not be empty even with negative focus index")
}
// Test with out-of-bounds positive index
m.focusIndex = 99
view = m.View()
if view == "" {
t.Error("View should not be empty even with out-of-bounds focus index")
}
}
// TestUpdateDescriptionWithSingleCharInMonthField verifies that a single invalid
// character in a field produces an appropriate error message.
func TestUpdateDescriptionWithSingleCharInMonthField(t *testing.T) {
t.Parallel()
m := initialModel()
// Set month field (index 3) to a single character
m.inputs[3].SetValue("a")
// This should not panic - it should set an error instead
m.updateDescription()
if m.err == nil {
t.Error("Expected an error for single character in month field, but got nil")
}
if !strings.Contains(m.err.Error(), "month") {
t.Errorf("Expected error to contain 'month', but got '%s'", m.err.Error())
}
if m.description != "" {
t.Errorf("Expected empty description for invalid input, but got: %s", m.description)
}
if m.nextRun != "" {
t.Errorf("Expected empty nextRun for invalid input, but got: %s", m.nextRun)
}
}
// TestIsValidCronPart verifies the validation logic for cron expression parts,
// including wildcards, ranges, lists, step values, and month/weekday names.
func TestIsValidCronPart(t *testing.T) {
t.Parallel()
tests := []struct {
value string
fieldIndex int // 0=minute, 1=hour, 2=day, 3=month, 4=weekday
expected bool
}{
// Numeric fields (minute, hour, day)
{"*", 0, true},
{"", 0, true},
{"5", 0, true},
{"15", 1, true},
{"1-5", 0, true},
{"1,2,3", 0, true},
{"*/5", 0, true},
{"0-23", 1, true},
// Month field (3) - letters allowed
{"JAN-DEC", 3, true},
{"JAN", 3, true},
{"1-12", 3, true},
// Weekday field (4) - letters allowed
{"MON", 4, true},
{"SUN-SAT", 4, true},
{"0-6", 4, true},
// Invalid cases
{"a", 0, false}, // Single letter in minute field - invalid
{"S", 3, false}, // Single letter in month field - invalid
{"x", 4, false}, // Single letter in weekday field - invalid
{"!", 0, false}, // Single special char - invalid
{"*s", 0, false}, // Wildcard with trailing letter - invalid
{"1s", 0, false}, // Number with trailing letter - invalid
{"12x", 0, false}, // Number with trailing invalid letter - invalid
{"AB", 3, false}, // Two letter abbreviation - invalid
{"*a", 0, false}, // Wildcard with letter - invalid
{"*/", 0, false}, // Incomplete step value - invalid
// Letters in wrong fields
{"JAN", 0, false}, // Month name in minute field - invalid
{"MON", 0, false}, // Day name in minute field - invalid
{"JAN", 4, false}, // Month name in weekday field - invalid
{"MON", 3, false}, // Day name in month field - invalid
}
for _, tt := range tests {
result := isValidCronPart(tt.value, tt.fieldIndex)
if result != tt.expected {
t.Errorf("isValidCronPart(%q, field %d) = %v, expected %v", tt.value, tt.fieldIndex, result, tt.expected)
}
}
}
// TestInvalidFieldErrorMessages verifies that each input field generates
// the correct error message when an invalid value is provided.
func TestInvalidFieldErrorMessages(t *testing.T) {
t.Parallel()
fieldNames := []string{"minute", "hour", "day", "month", "weekday"}
for i, fieldName := range fieldNames {
m := initialModel()
// Set invalid single character in the field
m.inputs[i].SetValue("x")
m.updateDescription()
if m.err == nil {
t.Errorf("Expected an error for invalid value in %s field, but got nil", fieldName)
continue
}
// Check that the error contains the field name
if !strings.Contains(m.err.Error(), fieldName) {
t.Errorf("Expected error message to contain '%s', but got '%s'", fieldName, m.err.Error())
}
}
}
// TestUpdateDescriptionWithValidCronExpressions verifies that valid cron expressions
// produce non-empty descriptions and next run times without errors.
func TestUpdateDescriptionWithValidCronExpressions(t *testing.T) {
t.Parallel()
tests := []struct {
name string
values []string
}{
{"Every minute", []string{"*", "*", "*", "*", "*"}},
{"Hourly at :30", []string{"30", "*", "*", "*", "*"}},
{"Daily at noon", []string{"0", "12", "*", "*", "*"}},
{"Weekly on Monday", []string{"0", "0", "*", "*", "MON"}},
{"Monthly on 1st", []string{"0", "0", "1", "*", "*"}},
{"With ranges", []string{"0-30", "9-17", "*", "*", "1-5"}},
{"With lists", []string{"0,15,30,45", "*", "*", "*", "*"}},
{"With steps", []string{"*/5", "*", "*", "*", "*"}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
m := initialModel()
for i, val := range tt.values {
m.inputs[i].SetValue(val)
}
m.updateDescription()
if m.err != nil {
t.Errorf("Expected no error for %s, but got: %v", tt.name, m.err)
}
if m.description == "" {
t.Errorf("Expected a description for %s, but got empty", tt.name)
}
if m.nextRun == "" {
t.Errorf("Expected nextRun for %s, but got empty", tt.name)
}
})
}
}
// TestUpdateDescriptionCaching verifies that updateDescription() avoids
// redundant computation when the cron expression hasn't changed.
func TestUpdateDescriptionCaching(t *testing.T) {
t.Parallel()
m := initialModel()
// Set initial values
m.inputs[0].SetValue("30")
m.updateDescription()
firstDesc := m.description
// Call updateDescription again without changing values
m.updateDescription()
// Should return early due to caching (lastCronExpr check)
if m.description != firstDesc {
t.Errorf("Description should remain the same due to caching")
}
}
// TestUpdateDescriptionWithInvalidCronParse verifies that semantically invalid
// values (like day 32) produce parser errors.
func TestUpdateDescriptionWithInvalidCronParse(t *testing.T) {
t.Parallel()
m := initialModel()
// Set valid format but semantically invalid value (day 32)
m.inputs[2].SetValue("32")
m.updateDescription()
// Should get an error from the parser
if m.err == nil {
t.Error("Expected an error for day value 32, but got nil")
}
if m.nextRun != "" {
t.Errorf("Expected empty nextRun for invalid day, but got: %s", m.nextRun)
}
}
// TestUpdateWithEnterKey verifies that pressing Enter advances the focus
// to the next input field.
func TestUpdateWithEnterKey(t *testing.T) {
t.Parallel()
m := initialModel()
m.focusIndex = 0
keyMsg := tea.KeyMsg{Type: tea.KeyEnter}
newModel, _ := m.Update(keyMsg)
m = assertModelType(t, newModel)
if m.focusIndex != 1 {
t.Errorf("Expected focus index to be 1 after Enter, but got %d", m.focusIndex)
}
}
// TestUpdateWithSpaceKey verifies that pressing Space advances the focus
// to the next input field.
func TestUpdateWithSpaceKey(t *testing.T) {
t.Parallel()
m := initialModel()
m.focusIndex = 2
keyMsg := tea.KeyMsg{Type: tea.KeySpace}
newModel, _ := m.Update(keyMsg)
m = assertModelType(t, newModel)
if m.focusIndex != 3 {
t.Errorf("Expected focus index to be 3 after Space, but got %d", m.focusIndex)
}
}
// TestUpdateWithEscKey verifies that pressing Esc triggers the quit command.
func TestUpdateWithEscKey(t *testing.T) {
t.Parallel()
m := initialModel()
keyMsg := tea.KeyMsg{Type: tea.KeyEsc}
_, cmd := m.Update(keyMsg)
// Should return tea.Quit command
if cmd == nil {
t.Error("Expected a quit command for Esc key")
}
}
// TestUpdateInputsMultipleCalls verifies that multiple character inputs
// are properly accumulated in the focused field.
func TestUpdateInputsMultipleCalls(t *testing.T) {
t.Parallel()
m := initialModel()
m.focusIndex = 1
m.inputs[0].Blur()
m.inputs[1].Focus()
// Type multiple characters
for _, char := range "15" {
keyMsg := tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{char}}
newModel, _ := m.Update(keyMsg)
m = assertModelType(t, newModel)
}
expectedValue := "415" // Initial was "4", added "15"
if m.inputs[1].Value() != expectedValue {
t.Errorf("Expected input 1 to have value \"%s\", but got \"%s\"", expectedValue, m.inputs[1].Value())
}
}
// TestBackspaceOnFirstInput verifies that backspace on the first field
// with empty value doesn't move focus backward (no wraparound).
func TestBackspaceOnFirstInput(t *testing.T) {
t.Parallel()
m := initialModel()
m.focusIndex = 0
m.inputs[0].SetValue("")
keyMsg := tea.KeyMsg{Type: tea.KeyBackspace}
newModel, _ := m.Update(keyMsg)
m = assertModelType(t, newModel)
// Should remain at index 0 since we can't go back further
if m.focusIndex != 0 {
t.Errorf("Expected focus index to remain at 0, but got %d", m.focusIndex)
}
}
// TestViewWithDescription verifies that the View renders both the description
// and next run time when they are present.
func TestViewWithDescription(t *testing.T) {
t.Parallel()
m := initialModel()
m.width = 100
m.description = "Test description"
m.nextRun = "2025-10-21 12:00:00"
view := m.View()
if !strings.Contains(view, "Test description") {
t.Error("View should contain the description")
}
if !strings.Contains(view, "2025-10-21 12:00:00") {
t.Error("View should contain the nextRun time")
}
}
// TestViewFocusedInputStyling verifies that the focused input's label
// is rendered with the appropriate styling.
func TestViewFocusedInputStyling(t *testing.T) {
t.Parallel()
m := initialModel()
m.width = 100
m.focusIndex = 2
// Focus the third input
for i := range m.inputs {
m.inputs[i].Blur()
}
m.inputs[2].Focus()
view := m.View()
// Should contain the "day" label
if !strings.Contains(view, "day") {
t.Error("View should contain focused field label")
}
}
// TestInitialModelWithError verifies that initialModel() always returns
// a valid model structure (error handling is tested elsewhere).
func TestInitialModelWithError(t *testing.T) {
t.Parallel()
// This tests the error path in initialModel when cron descriptor creation fails
// In normal circumstances this shouldn't fail, but we test the structure
m := initialModel()
// Skip the rest of the test if model is nil (should never happen)
if m == nil {
t.Fatal("initialModel should not return nil")
return
}
if len(m.inputs) != 5 {
t.Errorf("Expected 5 inputs, got %d", len(m.inputs))
}
}
// TestIsValidCronPartEdgeCases tests additional edge cases for cron part validation,
// including step values, ranges, and month/weekday names.
func TestIsValidCronPartEdgeCases(t *testing.T) {
t.Parallel()
tests := []struct {
value string
fieldIndex int
expected bool
}{
{"*/10", 0, true}, // Step value with 2 digits
{"*/100", 0, true}, // Step value with 3 digits
{"*/*", 0, false}, // Invalid step
{"*/x", 0, false}, // Invalid step with letter
{"1-5/2", 0, true}, // Range with step
{"MON-FRI", 4, true}, // Day range (weekday field)
{"JAN", 3, true}, // Month abbreviation (month field)
{"JANUARY", 3, true}, // Full month name (contains JAN, month field)
{"XYZ", 3, false}, // Invalid abbreviation
{"1,2,3,4,5", 0, true}, // Long list
{"0", 0, true}, // Zero
{"59", 0, true}, // Two digit number
{"123", 2, true}, // Three digit number (day field can go higher than 31 in ranges)
}
for _, tt := range tests {
result := isValidCronPart(tt.value, tt.fieldIndex)
if result != tt.expected {
t.Errorf("isValidCronPart(%q, field %d) = %v, expected %v", tt.value, tt.fieldIndex, result, tt.expected)
}
}
}
// TestIsValidCronPartMoreEdgeCases tests additional validation scenarios
// for special characters and invalid patterns.
func TestIsValidCronPartMoreEdgeCases(t *testing.T) {
t.Parallel()
tests := []struct {
value string
fieldIndex int
expected bool
}{
{"#", 0, false}, // Invalid special character
{"@", 0, false}, // Invalid special character
{"5-10", 0, true}, // Valid range
{"TUE", 4, true}, // Day abbreviation (weekday field)
{"TUESDAY", 4, true}, // Contains valid abbreviation (weekday field)
{"AB", 3, false}, // Invalid two-letter combo
{"1a", 0, false}, // Number with invalid letter
{"10x", 0, false}, // Number with trailing invalid letter
}
for _, tt := range tests {
result := isValidCronPart(tt.value, tt.fieldIndex)
if result != tt.expected {
t.Errorf("isValidCronPart(%q, field %d) = %v, expected %v", tt.value, tt.fieldIndex, result, tt.expected)
}
}
}
// TestUpdateDescriptionEmptyAfterClear verifies that empty values are treated
// as wildcards (*) and still produce valid descriptions.
func TestUpdateDescriptionEmptyAfterClear(t *testing.T) {
t.Parallel()
m := initialModel()
// First set valid values
m.inputs[0].SetValue("30")
m.updateDescription()
if m.description == "" {
t.Error("Expected description after setting valid value")
}
// Now clear all but one to test empty value conversion
m.inputs[1].SetValue("")
m.inputs[2].SetValue("")
m.updateDescription()
// Empty values should be treated as *, so still valid
if m.err != nil {
t.Errorf("Expected no error with empty values, but got: %v", m.err)
}
}
// TestUpdateWithBackspaceOnNonEmptyInput verifies that backspace on a non-empty
// input field doesn't move focus backward.
func TestUpdateWithBackspaceOnNonEmptyInput(t *testing.T) {
t.Parallel()
m := initialModel()
m.focusIndex = 1
m.inputs[1].SetValue("10") // Non-empty value
m.inputs[0].Blur()
m.inputs[1].Focus()
keyMsg := tea.KeyMsg{Type: tea.KeyBackspace}
newModel, _ := m.Update(keyMsg)
m = assertModelType(t, newModel)
// Should stay at index 1 since value is not empty
if m.focusIndex != 1 {
t.Errorf("Expected focus index to remain at 1, but got %d", m.focusIndex)
}
}
// TestUpdateFocusIndexOutOfBoundsRecovery verifies that the Update method
// can recover from an artificially out-of-bounds focus index.
func TestUpdateFocusIndexOutOfBoundsRecovery(t *testing.T) {
t.Parallel()
m := initialModel()
// Artificially set focus index out of bounds
m.focusIndex = 10
// Update should reset it
keyMsg := tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("5")}
newModel, _ := m.Update(keyMsg)
m = assertModelType(t, newModel)
// Should be reset to 0
if m.focusIndex != 0 {
t.Errorf("Expected focus index to be reset to 0, but got %d", m.focusIndex)
}
}
// TestShiftTabFromLastToFirst verifies that Shift+Tab from the last input
// wraps around to the first input.
func TestShiftTabFromLastToFirst(t *testing.T) {
t.Parallel()
m := initialModel()
// Move to last input
m.focusIndex = 4
for i := range m.inputs {
m.inputs[i].Blur()
}
m.inputs[4].Focus()
// Press shift+tab
keyMsg := tea.KeyMsg{Type: tea.KeyShiftTab}
newModel, _ := m.Update(keyMsg)
m = assertModelType(t, newModel)
if m.focusIndex != 3 {
t.Errorf("Expected focus index to be 3 after shift+tab from 4, but got %d", m.focusIndex)
}
}
// TestTabWraparound verifies that pressing Tab from the last input
// wraps around to the first input.
func TestTabWraparound(t *testing.T) {
t.Parallel()
m := initialModel()
// Move to last input
m.focusIndex = 4
for i := range m.inputs {
m.inputs[i].Blur()
}
m.inputs[4].Focus()
// Press tab - should wrap to 0
keyMsg := tea.KeyMsg{Type: tea.KeyTab}
newModel, _ := m.Update(keyMsg)
m = assertModelType(t, newModel)
if m.focusIndex != 0 {
t.Errorf("Expected focus index to wrap to 0 after tab from 4, but got %d", m.focusIndex)
}
}
// TestValidCronPartWildcardWithNonSlash verifies that wildcards followed by
// non-slash characters are rejected as invalid.
func TestValidCronPartWildcardWithNonSlash(t *testing.T) {
t.Parallel()
// This tests the defensive check in isValidCronPart for wildcard followed by non-slash
result := isValidCronPart("*a", 0)
if result != false {
t.Error("Expected false for '*a', but got true")
}
result = isValidCronPart("*x", 0)
if result != false {
t.Error("Expected false for '*x', but got true")
}
result = isValidCronPart("*5", 0)
if result != false {
t.Error("Expected false for '*5', but got true")
}
}
// TestUpdateDescriptionWithAllWhitespace verifies the behavior when input
// fields contain only whitespace (which gets trimmed to empty, then converted to *).
func TestUpdateDescriptionWithAllWhitespace(t *testing.T) {
t.Parallel()
m := initialModel()
// This is hard to trigger since empty inputs are converted to "*"
// But we can test by setting lastCronExpr to something and then trying whitespace
m.lastCronExpr = ""
// Set inputs to spaces (though the textinput might not allow this)
// This test documents the intent even if the line is hard to reach
for i := range m.inputs {
m.inputs[i].SetValue(" ")