github.com/krzko/gosh@v0.0.0-20241128233202-5abd4ef06633/internal/shell/parser/parser_test.go (about)

     1  // internal/shell/parser/parser_test.go
     2  package parser
     3  
     4  import (
     5  	"testing"
     6  )
     7  
     8  func TestParser(t *testing.T) {
     9  	tests := []struct {
    10  		name     string
    11  		input    string
    12  		wantCmd  string
    13  		wantArgs []string
    14  		wantPipe bool
    15  	}{
    16  		{
    17  			name:     "simple command",
    18  			input:    "ls -l",
    19  			wantCmd:  "ls",
    20  			wantArgs: []string{"-l"},
    21  			wantPipe: false,
    22  		},
    23  		{
    24  			name:     "command with quotes",
    25  			input:    `echo "hello world"`,
    26  			wantCmd:  "echo",
    27  			wantArgs: []string{"hello world"},
    28  			wantPipe: false,
    29  		},
    30  		{
    31  			name:     "command with pipe",
    32  			input:    "ls -l | grep foo",
    33  			wantCmd:  "ls",
    34  			wantArgs: []string{"-l"},
    35  			wantPipe: true,
    36  		},
    37  		{
    38  			name:     "command with escaped characters",
    39  			input:    `echo hello\ world`,
    40  			wantCmd:  "echo",
    41  			wantArgs: []string{"hello world"},
    42  			wantPipe: false,
    43  		},
    44  	}
    45  
    46  	parser := New()
    47  
    48  	for _, tt := range tests {
    49  		t.Run(tt.name, func(t *testing.T) {
    50  			cmd, err := parser.Parse(tt.input)
    51  			if err != nil {
    52  				t.Fatalf("Parse() error = %v", err)
    53  			}
    54  
    55  			if cmd.Name != tt.wantCmd {
    56  				t.Errorf("Parse() command = %v, want %v", cmd.Name, tt.wantCmd)
    57  			}
    58  
    59  			if len(cmd.Args) != len(tt.wantArgs) {
    60  				t.Errorf("Parse() args length = %v, want %v", len(cmd.Args), len(tt.wantArgs))
    61  			}
    62  
    63  			for i, arg := range cmd.Args {
    64  				if arg != tt.wantArgs[i] {
    65  					t.Errorf("Parse() arg[%d] = %v, want %v", i, arg, tt.wantArgs[i])
    66  				}
    67  			}
    68  
    69  			hasPipe := cmd.Pipe != nil
    70  			if hasPipe != tt.wantPipe {
    71  				t.Errorf("Parse() pipe = %v, want %v", hasPipe, tt.wantPipe)
    72  			}
    73  		})
    74  	}
    75  }