|
| 1 | +package sketch |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "testing" |
| 6 | + |
| 7 | + "github.com/arduino/arduino-cli/rpc/cc/arduino/cli/commands/v1" |
| 8 | + "github.com/stretchr/testify/require" |
| 9 | +) |
| 10 | + |
| 11 | +func Test_SketchNameWrongPattern(t *testing.T) { |
| 12 | + invalidNames := []string{ |
| 13 | + "&", |
| 14 | + "", |
| 15 | + ".hello", |
| 16 | + "_hello", |
| 17 | + "-hello", |
| 18 | + "hello*", |
| 19 | + "||||||||||||||", |
| 20 | + ",`hack[}attempt{];", |
| 21 | + } |
| 22 | + for _, name := range invalidNames { |
| 23 | + _, err := NewSketch(context.Background(), &commands.NewSketchRequest{ |
| 24 | + SketchName: name, |
| 25 | + SketchDir: t.TempDir(), |
| 26 | + }) |
| 27 | + require.NotNil(t, err) |
| 28 | + |
| 29 | + require.Error(t, err, `Can't create sketch: invalid sketch name "%s". Required pattern %s`, |
| 30 | + name, |
| 31 | + sketchNameValidationRegex) |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +func Test_SketchNameEmpty(t *testing.T) { |
| 36 | + emptyName := "" |
| 37 | + _, err := NewSketch(context.Background(), &commands.NewSketchRequest{ |
| 38 | + SketchName: emptyName, |
| 39 | + SketchDir: t.TempDir(), |
| 40 | + }) |
| 41 | + require.NotNil(t, err) |
| 42 | + |
| 43 | + require.Error(t, err, `Can't create sketch: sketch name cannot be empty`) |
| 44 | +} |
| 45 | + |
| 46 | +func Test_SketchNameTooLong(t *testing.T) { |
| 47 | + tooLongName := make([]byte, sketchNameMaxLength+1) |
| 48 | + for i := range tooLongName { |
| 49 | + tooLongName[i] = 'a' |
| 50 | + } |
| 51 | + _, err := NewSketch(context.Background(), &commands.NewSketchRequest{ |
| 52 | + SketchName: string(tooLongName), |
| 53 | + SketchDir: t.TempDir(), |
| 54 | + }) |
| 55 | + require.NotNil(t, err) |
| 56 | + |
| 57 | + require.Error(t, err, `Can't create sketch: sketch name too long (%d characters). Maximum allowed length is %d`, |
| 58 | + len(tooLongName), |
| 59 | + sketchNameMaxLength) |
| 60 | +} |
| 61 | + |
| 62 | +func Test_SketchNameOk(t *testing.T) { |
| 63 | + lengthLimitName := make([]byte, sketchNameMaxLength) |
| 64 | + for i := range lengthLimitName { |
| 65 | + lengthLimitName[i] = 'a' |
| 66 | + } |
| 67 | + validNames := []string{ |
| 68 | + "h", |
| 69 | + "h.ello", |
| 70 | + "h..ello-world", |
| 71 | + "h..ello-world.", |
| 72 | + "hello_world__", |
| 73 | + string(lengthLimitName), |
| 74 | + } |
| 75 | + for _, name := range validNames { |
| 76 | + _, err := NewSketch(context.Background(), &commands.NewSketchRequest{ |
| 77 | + SketchName: name, |
| 78 | + SketchDir: t.TempDir(), |
| 79 | + }) |
| 80 | + require.Nil(t, err) |
| 81 | + } |
| 82 | +} |
0 commit comments