@@ -17,15 +17,20 @@ limitations under the License.
1717package envtest
1818
1919import (
20+ "context"
2021 "fmt"
2122 "os"
2223 "strings"
2324 "time"
2425
26+ corev1 "k8s.io/api/core/v1"
2527 apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
2628 "k8s.io/apimachinery/pkg/runtime"
29+ "k8s.io/apimachinery/pkg/types"
30+ "k8s.io/apimachinery/pkg/util/wait"
2731 "k8s.io/client-go/kubernetes/scheme"
2832 "k8s.io/client-go/rest"
33+ "sigs.k8s.io/controller-runtime/pkg/client"
2934
3035 "sigs.k8s.io/controller-runtime/pkg/client/config"
3136 logf "sigs.k8s.io/controller-runtime/pkg/internal/log"
@@ -265,6 +270,12 @@ func (te *Environment) Start() (*rest.Config, error) {
265270 te .Scheme = scheme .Scheme
266271 }
267272
273+ // If we are bringing etcd up for the first time, it can take some time for the
274+ // default namespace to actually be created and seen as available to the apiserver
275+ if err := te .waitForDefaultNamespace (te .Config ); err != nil {
276+ return nil , fmt .Errorf ("default namespace didn't register within deadline: %w" , err )
277+ }
278+
268279 // Call PrepWithoutInstalling to setup certificates first
269280 // and have them available to patch CRD conversion webhook as well.
270281 if err := te .WebhookInstallOptions .PrepWithoutInstalling (); err != nil {
@@ -322,6 +333,20 @@ func (te *Environment) startControlPlane() error {
322333 return nil
323334}
324335
336+ func (te * Environment ) waitForDefaultNamespace (config * rest.Config ) error {
337+ cs , err := client .New (config , client.Options {})
338+ if err != nil {
339+ return fmt .Errorf ("unable to create client: %w" , err )
340+ }
341+ // It shouldn't take longer than 5s for the default namespace to be brought up in etcd
342+ return wait .PollUntilContextTimeout (context .TODO (), time .Millisecond * 50 , time .Second * 5 , true , func (ctx context.Context ) (bool , error ) {
343+ if err = cs .Get (ctx , types.NamespacedName {Name : "default" }, & corev1.Namespace {}); err != nil {
344+ return false , nil //nolint:nilerr
345+ }
346+ return true , nil
347+ })
348+ }
349+
325350func (te * Environment ) defaultTimeouts () error {
326351 var err error
327352 if te .ControlPlaneStartTimeout == 0 {
0 commit comments