Skip to content

Commit 0d573cc

Browse files
Enhance input validation in Rock Paper Scissors game and update tests
1 parent 26f2a33 commit 0d573cc

2 files changed

Lines changed: 26 additions & 4 deletions

File tree

internal/rockpaperscissors/rockpaperscissors.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,5 +170,11 @@ func PlayGame(prompter Prompter) {
170170
func parseInt(s string) int {
171171
val := 3 // Default value
172172
fmt.Sscanf(s, "%d", &val)
173+
if val <= 0 {
174+
return 3
175+
}
176+
if val%2 == 0 {
177+
val++ // Convert even numbers to next odd number
178+
}
173179
return val
174180
}

internal/rockpaperscissors/rockpaperscissors_test.go

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -347,31 +347,27 @@ func TestPlayGame(t *testing.T) {
347347
returns: []int{1, 0, 0, 0}, // Select 5 rounds, then rock three times
348348
errors: []error{nil, nil, nil, nil},
349349
},
350-
wantGameOver: true,
351350
},
352351
{
353352
name: "Error on rounds selection",
354353
prompter: &mockPromptSequence{
355354
returns: []int{0},
356355
errors: []error{fmt.Errorf("mock error")},
357356
},
358-
wantGameOver: true,
359357
},
360358
{
361359
name: "Error on move selection",
362360
prompter: &mockPromptSequence{
363361
returns: []int{0, 0},
364362
errors: []error{nil, fmt.Errorf("mock error")},
365363
},
366-
wantGameOver: true,
367364
},
368365
{
369366
name: "Invalid round index",
370367
prompter: &mockPromptSequence{
371368
returns: []int{99, 3}, // Invalid round index, then exit
372369
errors: []error{nil, nil},
373370
},
374-
wantGameOver: true,
375371
},
376372
}
377373

@@ -398,6 +394,26 @@ func TestParseInt(t *testing.T) {
398394
input: "invalid",
399395
want: 3,
400396
},
397+
{
398+
name: "Empty input returns default",
399+
input: "",
400+
want: 3,
401+
},
402+
{
403+
name: "Negative number returns default",
404+
input: "-1",
405+
want: 3,
406+
},
407+
{
408+
name: "Zero returns default",
409+
input: "0",
410+
want: 3,
411+
},
412+
{
413+
name: "Even number returns next odd number",
414+
input: "4",
415+
want: 5,
416+
},
401417
}
402418
for _, tt := range tests {
403419
t.Run(tt.name, func(t *testing.T) {

0 commit comments

Comments
 (0)