github.com/emcfarlane/larking@v0.0.0-20220605172417-1704b45ee6c3/cmd/lark/main_test.go (about)

     1  package main
     2  
     3  import (
     4  	"context"
     5  	"io/ioutil"
     6  	"os"
     7  	"testing"
     8  )
     9  
    10  func TestBoot(t *testing.T) {
    11  	content := []byte("1+1\n")
    12  	tmpin, err := ioutil.TempFile("", "bootin")
    13  	if err != nil {
    14  		t.Fatal(err)
    15  	}
    16  	defer os.Remove(tmpin.Name()) // clean up
    17  	defer tmpin.Close()
    18  
    19  	if _, err := tmpin.Write(content); err != nil {
    20  		t.Fatal(err)
    21  	}
    22  
    23  	if _, err := tmpin.Seek(0, 0); err != nil {
    24  		t.Fatal(err)
    25  	}
    26  
    27  	oldStdin := os.Stdin
    28  	defer func() { os.Stdin = oldStdin }() // Restore original Stdin
    29  	os.Stdin = tmpin
    30  
    31  	tmpout, err := ioutil.TempFile("", "bootout")
    32  	if err != nil {
    33  		t.Fatal(err)
    34  	}
    35  	defer os.Remove(tmpout.Name()) // clean up
    36  	defer tmpout.Close()
    37  
    38  	oldStdout := os.Stdout
    39  	defer func() { os.Stdout = oldStdout }() // Restore original Stdout
    40  	os.Stdout = tmpout
    41  
    42  	ctx, cancel := context.WithCancel(context.Background())
    43  	defer cancel()
    44  
    45  	opts := &Options{}
    46  	if err := run(ctx, opts); err != nil {
    47  		t.Fatal(err)
    48  	}
    49  	b, err := ioutil.ReadFile(tmpout.Name())
    50  	if err != nil {
    51  		t.Fatal(err)
    52  	}
    53  	t.Log("\n" + string(b))
    54  }
    55  
    56  func TestBootFile(t *testing.T) {
    57  	ctx, cancel := context.WithCancel(context.Background())
    58  	defer cancel()
    59  
    60  	opts := &Options{
    61  		Filename: "<stdin>",
    62  		Source:   "a = 1+1",
    63  	}
    64  	if err := exec(ctx, opts); err != nil {
    65  		t.Fatal(err)
    66  	}
    67  }