#fstest for invalid file

16 messages · Page 1 of 1 (latest)

rotund idol
deep shoal
#

So the purpose of this program is to get the keys from a json file? is that right

rotund idol
fleet void
#

Why do you want to test io.ReadAll?

rotund idol
#

Therefore I was asked to also provide a testcase for the code containing io.ReadAll

rotund idol
fleet void
#

You mean coverage for the code inside the if-statement?

rotund idol
#

I am rather new to code testing in go 😅

fleet void
#

You can't make it fail unless the system is completely broken and can't read things

#

Or you need to mock the fs.FS where reading fails

#

Also, instead of reading all of it and then unmarshal, you can do this:

func getKeys(fileSystem fs.FS) (CiscoKey, error) {
    file, err := fileSystem.Open("key.json")
    if err != nil {
        log.Error().Err(err).Msg("Could not open key.json File")
        return nil, err
    }

    defer file.Close()

    decoder := json.NewDecoder(file)

    var ciscoKey CiscoKey

    if err = decoder.Decode(&ciscoKey); err != nil {
        log.Error().Err(err).Msg("Error while unmarshal of JSON")
        return nil, err
    }

    return ciscoKey, nil
}

And to test it, you need to mock fs.FS.

fleet void
fleet void
#

It will fail to open if the file doesn't exist in the map. Read will fail with io.UnexpectedEOF if the data is nil, so you can test both missing file and failed read.

However, ask yourself, do you really want to get coverage for that part?

rotund idol