2021-01-04 15:44:37 +03:00
package utils_test
2019-11-06 04:14:21 +03:00
import (
"errors"
"math"
"testing"
"github.com/spf13/afero"
"github.com/stretchr/testify/assert"
2021-01-04 15:44:37 +03:00
"github.com/stretchr/testify/require"
"github.com/aquasecurity/vuln-list-update/utils"
2019-11-06 04:14:21 +03:00
)
2021-01-04 15:44:37 +03:00
func TestWriteJSON ( t * testing . T ) {
2019-11-06 04:14:21 +03:00
testCases := [ ] struct {
name string
2019-11-06 18:09:59 +03:00
fs afero . Fs
2019-11-06 04:14:21 +03:00
inputData interface { }
2019-11-06 18:09:59 +03:00
expectedData string
2019-11-06 04:14:21 +03:00
expectedError error
} {
{
2019-11-06 18:09:59 +03:00
name : "happy path" ,
fs : afero . NewMemMapFs ( ) ,
inputData : struct {
A string
B int
} { A : "foo" , B : 1 } ,
expectedData : "{\n \"A\": \"foo\",\n \"B\": 1\n}" ,
2019-11-06 04:14:21 +03:00
} ,
{
2019-11-06 18:09:59 +03:00
name : "sad path: fs.AppFs.Create returns an error" ,
fs : afero . NewReadOnlyFs ( afero . NewMemMapFs ( ) ) ,
2021-01-04 15:44:37 +03:00
expectedError : errors . New ( "unable to create a directory: operation not permitted" ) ,
2019-11-06 04:14:21 +03:00
} ,
{
name : "sad path: bad json input data" ,
2019-11-06 18:09:59 +03:00
fs : afero . NewMemMapFs ( ) ,
2019-11-06 04:14:21 +03:00
inputData : math . NaN ( ) ,
expectedError : errors . New ( "failed to marshal JSON: json: unsupported value: NaN" ) ,
} ,
}
for _ , tc := range testCases {
2021-01-04 15:44:37 +03:00
err := utils . WriteJSON ( tc . fs , "dir" , "file" , tc . inputData )
2019-11-06 04:14:21 +03:00
switch {
case tc . expectedError != nil :
2021-01-04 15:44:37 +03:00
require . NotNil ( t , err )
2019-11-06 04:14:21 +03:00
assert . Equal ( t , tc . expectedError . Error ( ) , err . Error ( ) , tc . name )
2019-11-06 18:09:59 +03:00
return
2019-11-06 04:14:21 +03:00
default :
assert . NoError ( t , err , tc . name )
}
2021-01-04 15:44:37 +03:00
actual , err := afero . ReadFile ( tc . fs , "dir/file" )
2019-11-06 18:09:59 +03:00
assert . NoError ( t , err , tc . name )
assert . Equal ( t , tc . expectedData , string ( actual ) , tc . name )
}
2019-11-06 04:14:21 +03:00
}