kubernetes / client-go

Go client for Kubernetes.
Apache License 2.0
8.78k stars 2.9k forks source link

[Question] fake client can't get resource from all namespace #1320

Closed dayeguilaiye closed 7 months ago

dayeguilaiye commented 7 months ago

When I testing with fake client, I want to get all service:

func TestName(t *testing.T) {
    client := fake.NewSimpleClientset()
    _, err := client.CoreV1().Services("test-namespace").
        Create(
            context.Background(),
            &v1.Service{ObjectMeta: v12.ObjectMeta{
                Name: "test-service",
            }},
            v12.CreateOptions{})
    if err != nil {
        panic(err)
    }
    _, err = client.CoreV1().Services("").
        Get(
            context.Background(),
            "test-service",
            v12.GetOptions{},
        )
    if err != nil {
        panic(err)
    }
}

It failed with error: services "test-service" not found

And when I change client.CoreV1().Services("").Get into client.CoreV1().Services("test-namespace").Get, it success.

But as I know, calling Services("").Get means find in all namespace.

I found the code where really doing the getting:

https://github.com/kubernetes/client-go/blob/84a6fe7e4032ae1b8bc03b5208e771c5f7103549/testing/fixture.go#L286-L313

Seems like it just use the namespace as a part of the key in a map, which will cause this problem.

Is this designed as this or a bug? Or am I wrong? Only Services("").List means list in all namespace, Services("").Get just means get in default namespace instead of all namespace.

liggitt commented 7 months ago

only Services("").List means list in all namespaces

Services("...").Get only returns a single object and must specify an actual namespace when getting a type that is defined to be namespaced (like services are)