...

Source file src/github.com/go-openapi/analysis/internal/antest/helpers_test.go

Documentation: github.com/go-openapi/analysis/internal/antest

     1  package antest
     2  
     3  import (
     4  	"os"
     5  	"testing"
     6  
     7  	"github.com/stretchr/testify/require"
     8  )
     9  
    10  func TestLongTestEnabled(t *testing.T) {
    11  	t.Run("should be false by default", func(t *testing.T) {
    12  		require.False(t, LongTestsEnabled())
    13  	})
    14  }
    15  
    16  func TestLoadSpecErrorCases(t *testing.T) {
    17  	t.Run("should not load invalid path", func(t *testing.T) {
    18  		_, err := LoadSpec("nowhere.json")
    19  		require.Error(t, err)
    20  	})
    21  
    22  	t.Run("should not load invalid YAML", func(t *testing.T) {
    23  		invalidYAMLFile, clean := prepareBadDoc(t, "yaml", true)
    24  		t.Cleanup(clean)
    25  
    26  		_, err := LoadSpec(invalidYAMLFile)
    27  		require.Error(t, err)
    28  	})
    29  
    30  	t.Run("should not load invalid JSON", func(t *testing.T) {
    31  		invalidJSONFile, clean := prepareBadDoc(t, "json", true)
    32  		t.Cleanup(clean)
    33  
    34  		_, err := LoadSpec(invalidJSONFile)
    35  		require.Error(t, err)
    36  	})
    37  
    38  	t.Run("should not load invalid spec", func(t *testing.T) {
    39  		invalidJSONFile, clean := prepareBadDoc(t, "json", false)
    40  		t.Cleanup(clean)
    41  
    42  		_, err := LoadSpec(invalidJSONFile)
    43  		require.Error(t, err)
    44  	})
    45  }
    46  
    47  func prepareBadDoc(t testing.TB, kind string, invalidFormat bool) (string, func()) {
    48  	t.Helper()
    49  
    50  	var (
    51  		file string
    52  		data []byte
    53  	)
    54  
    55  	switch kind {
    56  	case "yaml", "yml":
    57  		f, err := os.CreateTemp("", "*.yaml")
    58  		require.NoError(t, err)
    59  		file = f.Name()
    60  
    61  		if invalidFormat {
    62  			data = []byte(`--
    63  zig:
    64    zag 3, 4
    65  `)
    66  		} else {
    67  			data = []byte(`--
    68  swagger: 2
    69  info:
    70    title: true
    71  `)
    72  		}
    73  
    74  	case "json":
    75  		f, err := os.CreateTemp("", "*.json")
    76  		require.NoError(t, err)
    77  		file = f.Name()
    78  
    79  		if invalidFormat {
    80  			data = []byte(`{
    81  "zig": {
    82    "zag"
    83  }`)
    84  		} else {
    85  			data = []byte(`{
    86  "swagger": 2
    87  "info": {
    88    "title": true
    89  }
    90  }`)
    91  		}
    92  
    93  	default:
    94  		panic("supports only yaml or json")
    95  	}
    96  
    97  	require.NoError(t,
    98  		os.WriteFile(file, data, 0600),
    99  	)
   100  
   101  	return file, func() {
   102  		_ = os.RemoveAll(file)
   103  	}
   104  }
   105  

View as plain text