...

Source file src/github.com/pelletier/go-toml/cmd/tomljson/main_test.go

Documentation: github.com/pelletier/go-toml/cmd/tomljson

     1  package main
     2  
     3  import (
     4  	"bytes"
     5  	"io/ioutil"
     6  	"os"
     7  	"runtime"
     8  	"strings"
     9  	"testing"
    10  )
    11  
    12  func expectBufferEquality(t *testing.T, name string, buffer *bytes.Buffer, expected string) {
    13  	output := buffer.String()
    14  	if output != expected {
    15  		t.Errorf("incorrect %s:\n%s\n\nexpected %s:\n%s", name, output, name, expected)
    16  		t.Log([]rune(output))
    17  		t.Log([]rune(expected))
    18  	}
    19  }
    20  
    21  func expectProcessMainResults(t *testing.T, input string, args []string, exitCode int, expectedOutput string, expectedError string) {
    22  	inputReader := strings.NewReader(input)
    23  	outputBuffer := new(bytes.Buffer)
    24  	errorBuffer := new(bytes.Buffer)
    25  
    26  	returnCode := processMain(args, inputReader, outputBuffer, errorBuffer)
    27  
    28  	expectBufferEquality(t, "output", outputBuffer, expectedOutput)
    29  	expectBufferEquality(t, "error", errorBuffer, expectedError)
    30  
    31  	if returnCode != exitCode {
    32  		t.Error("incorrect return code:", returnCode, "expected", exitCode)
    33  	}
    34  }
    35  
    36  func TestProcessMainReadFromStdin(t *testing.T) {
    37  	input := `
    38  		[mytoml]
    39  		a = 42`
    40  	expectedOutput := `{
    41    "mytoml": {
    42      "a": 42
    43    }
    44  }
    45  `
    46  	expectedError := ``
    47  	expectedExitCode := 0
    48  
    49  	expectProcessMainResults(t, input, []string{}, expectedExitCode, expectedOutput, expectedError)
    50  }
    51  
    52  func TestProcessMainReadFromFile(t *testing.T) {
    53  	input := `
    54  		[mytoml]
    55  		a = 42`
    56  
    57  	tmpfile, err := ioutil.TempFile("", "example.toml")
    58  	if err != nil {
    59  		t.Fatal(err)
    60  	}
    61  	if _, err := tmpfile.Write([]byte(input)); err != nil {
    62  		t.Fatal(err)
    63  	}
    64  
    65  	defer os.Remove(tmpfile.Name())
    66  
    67  	expectedOutput := `{
    68    "mytoml": {
    69      "a": 42
    70    }
    71  }
    72  `
    73  	expectedError := ``
    74  	expectedExitCode := 0
    75  
    76  	expectProcessMainResults(t, ``, []string{tmpfile.Name()}, expectedExitCode, expectedOutput, expectedError)
    77  }
    78  
    79  func TestProcessMainReadFromMissingFile(t *testing.T) {
    80  	var expectedError string
    81  	if runtime.GOOS == "windows" {
    82  		expectedError = `open /this/file/does/not/exist: The system cannot find the path specified.
    83  `
    84  	} else {
    85  		expectedError = `open /this/file/does/not/exist: no such file or directory
    86  `
    87  	}
    88  
    89  	expectProcessMainResults(t, ``, []string{"/this/file/does/not/exist"}, -1, ``, expectedError)
    90  }
    91  

View as plain text