Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding extension for JUnit5 support #2320

Merged
merged 6 commits into from
Jul 1, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
#### Improvements
* Fix #2233: client.service().getUrl(..) should be able to fetch URL for ClusterIP based services
* Fix #2278: Added type parameters for KubernetesList in KubernetesClient + test verifying waitUntilCondition **always** retrieves resource from server
* Fix #2320: Added JUnit5 extension for mocking KubernetesClient in tests using @EnableKubernetesMockClient

#### Dependency Upgrade

Expand Down
29 changes: 29 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -346,7 +346,36 @@ Then you can use the server like:
assertTrue(closeLatch.await(1, TimeUnit.MINUTES));
}

### JUnit5 support through extension

You can use KubernetesClient mocking mechanism with JUnit5. Since it doesn't support `@Rule` and `@ClassRule` there is dedicated annotation `@EnableKubernetesMockClient`.
If you would like to create instance of mocked `KubernetesClient` for each test (JUnit4 `@Rule`) you need to declare instance of `KubernetesClient` as shown below.

@EnableKubernetesMockClient
class ExampleTest {

KubernetesClient client;

@Test
public void testInStandardMode() {
...
}
}

In case you would like to define static instance of mocked server per all the test (JUnit4 `@ClassRule`) you need to declare instance of `KubernetesClient` as shown below.
You can also enable crudMode by using annotation field `crud`.

@EnableKubernetesMockClient(crud = true)
class ExampleTest {

static KubernetesClient client;

@Test
public void testInCrudMode() {
...
}
}

## Compatibility Matrix

| | Kubernetes 1.4.9 | Kubernetes 1.6.0 | Kubernetes 1.7.0 | Kubernetes 1.9.0 | Kubernetes 1.10.0 | Kubernetes 1.11.0 | Kubernetes 1.12.0 | Kubernetes 1.14.2 | Kubernetes 1.15.3 | Kubernetes 1.17.0 |
Expand Down
4 changes: 4 additions & 0 deletions kubernetes-server-mock/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -65,5 +65,9 @@
<version>${slf4j.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
</dependency>
</dependencies>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package io.fabric8.kubernetes.client.server.mock;
/**
* Copyright (C) 2015 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import org.junit.jupiter.api.extension.ExtendWith;

import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
* Annotation that is used for enabling KubernetesMockServerExtension JUnit5 extension.
* You may set here two parameters of `KubernetesServer`: crudMode and https
*/
@Target({ TYPE, METHOD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@ExtendWith(KubernetesMockServerExtension.class)
public @interface EnableKubernetesMockClient {

boolean https() default true;

boolean crud() default false;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
/**
* Copyright (C) 2015 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package io.fabric8.kubernetes.client.server.mock;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Optional;

import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.NamespacedKubernetesClient;
import io.fabric8.mockwebserver.Context;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.jupiter.api.extension.AfterAllCallback;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeAllCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;

/**
* The class that implements JUnit5 extension mechanism. You can use it directly in your JUnit test
* by annotating it with `@ExtendWith(KubernetesMockServerExtension.class)` or through
* @EnableKubernetesMockClient annotation
*/
public class KubernetesMockServerExtension implements AfterEachCallback, AfterAllCallback, BeforeEachCallback, BeforeAllCallback {

private KubernetesMockServer mock;
private NamespacedKubernetesClient client;

@Override
public void afterEach(ExtensionContext context) throws Exception {
Optional<Class<?>> optClass = context.getTestClass();
if (optClass.isPresent()) {
Class<?> testClass = optClass.get();
if (findField(testClass, true) == null) {
destroy();
}
}
}

@Override
public void afterAll(ExtensionContext context) throws Exception {
destroy();
}

@Override
public void beforeEach(ExtensionContext context) throws Exception {
setKubernetesClientField(context, false);
}

@Override
public void beforeAll(ExtensionContext context) throws Exception {
setKubernetesClientField(context, true);
}

private void setKubernetesClientField(ExtensionContext context, boolean isStatic) throws IllegalAccessException {
Optional<Class<?>> optClass = context.getTestClass();
if (optClass.isPresent()) {
Class<?> testClass = optClass.get();
Field[] fields = testClass.getDeclaredFields();
for (Field f : fields) {
if (f.getType() == KubernetesClient.class && Modifier.isStatic(f.getModifiers()) == isStatic) {
createKubernetesClient(testClass);
f.setAccessible(true);
if (isStatic) {
f.set(null, client);
} else {
Optional<Object> optTestInstance = context.getTestInstance();
if (optTestInstance.isPresent())
f.set(optTestInstance.get(), client);
}
}
}
}
}

private void createKubernetesClient(Class<?> testClass) {
EnableKubernetesMockClient a = testClass.getAnnotation(EnableKubernetesMockClient.class);
mock = a.crud()
? new KubernetesMockServer(new Context(), new MockWebServer(), new HashMap<>(), new KubernetesCrudDispatcher(), a.https())
: new KubernetesMockServer(a.https());
mock.init();
client = mock.createClient();
}

private void destroy() {
mock.destroy();
client.close();
}

private Field findField(Class<?> testClass, boolean isStatic) {
Field[] fields = testClass.getDeclaredFields();
for (Field f : fields) {
if (f.getType() == KubernetesClient.class && Modifier.isStatic(f.getModifiers()) == isStatic) {
return f;
}
}
return null;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/**
* Copyright (C) 2015 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package io.fabric8.kubernetes.client.server.mock;

import io.fabric8.kubernetes.client.KubernetesClient;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

@EnableKubernetesMockClient(crud = true)
public class KubernetesMockServerExtensionStaticTests {

static KubernetesClient client;

@Test
void testExample() {
Assertions.assertNotNull(client);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/**
* Copyright (C) 2015 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package io.fabric8.kubernetes.client.server.mock;

import io.fabric8.kubernetes.client.KubernetesClient;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

@EnableKubernetesMockClient(crud = true)
public class KubernetesMockServerExtensionTests {

KubernetesClient client;

@Test
void testExample() {
Assertions.assertNotNull(client);
}
}