dnaeon / go-vcr

Record and replay your HTTP interactions for fast, deterministic and accurate tests

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

recorder.ModeReplaying not working as expected

whitehat101 opened this issue · comments

I was working on setting up testing for CI. I was hoping that if a cassette file was not present, the recorder would throw an error, which would prompt the developer to commit the missing file before their PR could be merged. This would let us run tests on CI while ensuring that no actual HTTP calls would occur.

We'd set the mode through a utility function, but the pseudo code looks like this:

import "github.com/dnaeon/go-vcr/v2/recorder"

vcr, err := recorder.NewAsMode("foo", recorder.ModeReplaying, nil)
if err != nil {
  log.Fatal(err)
}
// test using VCR
vcr.Stop()

No error occurred, and a new cassette file foo.yaml was created.

It looks like the bug may be in:

if mode != ModeDisabled {
// Depending on whether the cassette file exists or not we
// either create a new empty cassette or load from file
if _, err := os.Stat(cassetteFile); os.IsNotExist(err) || mode == ModeRecording {
// Create new cassette and enter in recording mode
c = cassette.New(cassetteName)
mode = ModeRecording

The mode is not ModeDisabled and no cassette file exists, so the mode is automatically reset to ModeRecording, then vcr.Stop() persists the cassette file, since the mode was changed to ModeRecording.

Hey @whitehat101 ,

Sorry for the late reply.

I believe this matches with the default behaviour of the recorder where if a cassette is missing it will hit the actual HTTP endpoint and record the interactions for the first time. Subsequent runs will use the recorded interactions instead.

I also think that what you have described is a valid use case, and for that we might have to introduce a new mode (e.g. ReplayOnly or something similar), which would match the behaviour you've described.

Unfortunately I don't have enough spare cycles these days, and not sure when I can spend some time implementing this one, but I'd be happy to review a PR if you submit one.

Thanks!

@dnaeon I'm happy to help with a PR for this, I'd like ReplayOnly too. Should I be making changes in the v2 directory?

Actually, just reading the code, isn't ModeReplayingOrRecording the mode where it replays and throws an error if it the cassette doesn't exist? Surely ModeReplaying should ONLY reply and throw an ErrInteractionNotFound if not found?