@@ -1225,3 +1225,82 @@ func TestInvalidRecorderMode(t *testing.T) {
12251225 t .Fatal ("expected recorder to fail with invalid mode" )
12261226 }
12271227}
1228+
1229+ func TestDiscardInteractionsOnSave (t * testing.T ) {
1230+ tests := []testCase {
1231+ {
1232+ method : http .MethodPost ,
1233+ body : "foo" ,
1234+ wantBody : "POST go-vcr\n foo" ,
1235+ wantStatus : http .StatusOK ,
1236+ wantContentLength : 15 ,
1237+ path : "/api/v1/foo" ,
1238+ },
1239+ {
1240+ method : http .MethodPost ,
1241+ body : "bar" ,
1242+ wantBody : "POST go-vcr\n bar" ,
1243+ wantStatus : http .StatusOK ,
1244+ wantContentLength : 15 ,
1245+ path : "/api/v1/bar" ,
1246+ },
1247+ }
1248+
1249+ server := newEchoHttpServer ()
1250+ serverUrl := server .URL
1251+
1252+ cassPath , err := newCassettePath ("test_discard_interactions_on_save" )
1253+ if err != nil {
1254+ t .Fatal (err )
1255+ }
1256+
1257+ // Create recorder
1258+ rec , err := recorder .New (cassPath )
1259+ if err != nil {
1260+ t .Fatal (err )
1261+ }
1262+
1263+ if rec .Mode () != recorder .ModeRecordOnce {
1264+ t .Fatal ("recorder is not in the correct mode" )
1265+ }
1266+
1267+ if rec .IsRecording () != true {
1268+ t .Fatal ("recorder is not recording" )
1269+ }
1270+
1271+ // The following hook function will be used to determine
1272+ // whether an interaction is to be discarded when saving the
1273+ // cassette on disk.
1274+ hook := func (i * cassette.Interaction ) error {
1275+ if i .Request .Method == http .MethodPost && i .Request .Body == "foo" {
1276+ i .DiscardOnSave = true
1277+ }
1278+
1279+ return nil
1280+ }
1281+ rec .AddHook (hook , recorder .AfterCaptureHook )
1282+
1283+ ctx := context .Background ()
1284+ client := rec .GetDefaultClient ()
1285+ for _ , test := range tests {
1286+ if err := test .run (client , ctx , serverUrl ); err != nil {
1287+ t .Fatal (err )
1288+ }
1289+ }
1290+
1291+ // Stop recorder and verify cassette
1292+ rec .Stop ()
1293+
1294+ cass , err := cassette .Load (cassPath )
1295+ if err != nil {
1296+ t .Fatal (err )
1297+ }
1298+
1299+ // We should have one interaction less than our test cases
1300+ // when reading the cassette from disk.
1301+ wantInteractions := len (tests ) - 1
1302+ gotInteractions := len (cass .Interactions )
1303+ if wantInteractions != gotInteractions {
1304+ t .Fatalf ("expected %d interactions, got %d" , wantInteractions , gotInteractions )
1305+ }
1306+ }
0 commit comments