Skip to content

Commit 232bcf0

Browse files
fix: handle invalid cache in IsNamespaced by resetting mapper
1 parent 562005d commit 232bcf0

2 files changed

Lines changed: 54 additions & 1 deletion

File tree

internal/tools/dynamic/dynamic.go

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,15 @@ func IsNamespaced(mapper meta.RESTMapper, gvk schema.GroupVersionKind) (bool, er
3838
}
3939
mapping, err := mapper.RESTMapping(gvk.GroupKind(), gvk.Version)
4040
if err != nil {
41-
return false, err
41+
if dm, ok := mapper.(interface{ Reset() }); ok {
42+
dm.Reset()
43+
mapping, err = mapper.RESTMapping(gvk.GroupKind(), gvk.Version)
44+
if err != nil {
45+
return false, err
46+
}
47+
} else {
48+
return false, err
49+
}
4250
}
4351

4452
if mapping.Scope.Name() == meta.RESTScopeNameRoot {

internal/tools/dynamic/dynamic_test.go

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package dynamic
22

33
import (
4+
"fmt"
45
"testing"
56

67
"k8s.io/apimachinery/pkg/api/meta"
@@ -193,6 +194,50 @@ func TestIsNamespaced_WithMockMapper(t *testing.T) {
193194
}
194195
}
195196

197+
type MockResettableMapper struct {
198+
*MockRESTMapper
199+
resetCalled bool
200+
failFirst bool
201+
}
202+
203+
func (m *MockResettableMapper) Reset() {
204+
m.resetCalled = true
205+
m.err = nil
206+
}
207+
208+
func (m *MockResettableMapper) RESTMapping(gk schema.GroupKind, versions ...string) (*meta.RESTMapping, error) {
209+
if m.failFirst && !m.resetCalled {
210+
return nil, fmt.Errorf("no matches for kind")
211+
}
212+
return m.MockRESTMapper.RESTMapping(gk, versions...)
213+
}
214+
215+
func TestIsNamespaced_WithCacheReset(t *testing.T) {
216+
gvk := schema.GroupVersionKind{
217+
Group: "example.com",
218+
Version: "v1",
219+
Kind: "Example",
220+
}
221+
222+
mock := &MockResettableMapper{
223+
MockRESTMapper: &MockRESTMapper{
224+
scopeName: meta.RESTScopeNameNamespace,
225+
},
226+
failFirst: true,
227+
}
228+
229+
got, err := IsNamespaced(mock, gvk)
230+
if err != nil {
231+
t.Errorf("IsNamespaced() unexpected error after reset = %v", err)
232+
}
233+
if got != true {
234+
t.Errorf("IsNamespaced() = %v, want %v", got, true)
235+
}
236+
if !mock.resetCalled {
237+
t.Error("IsNamespaced() did not call Reset() on mapper")
238+
}
239+
}
240+
196241
func TestIsNamespaced_EdgeCases(t *testing.T) {
197242
t.Run("empty GVK", func(t *testing.T) {
198243
mockMapper := &MockRESTMapper{

0 commit comments

Comments
 (0)