id
int64 0
929k
| file_name
stringlengths 6
110
| file_path
stringlengths 17
295
| content
stringlengths 49
9.72M
| size
int64 49
9.72M
| language
stringclasses 1
value | extension
stringclasses 1
value | total_lines
int64 1
202k
| avg_line_length
float64 3.25
49.6k
| max_line_length
int64 14
177k
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 7
61
| repo_stars
int64 66
33.1k
| repo_forks
int64 0
10.8k
| repo_open_issues
int64 0
1.42k
| repo_license
stringclasses 10
values | repo_extraction_date
stringclasses 22
values | exact_duplicates_stackv2
bool 2
classes | exact_duplicates_stackv1
bool 2
classes | exact_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | near_duplicates_stackv2
bool 2
classes | near_duplicates_redpajama
bool 2
classes | near_duplicates_stackv1
bool 2
classes |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | PathPrefixPredicateTest.java | halo-dev_halo/application/src/test/java/run/halo/app/PathPrefixPredicateTest.java | package run.halo.app;
import static org.assertj.core.api.Assertions.assertThat;
import java.net.URI;
import org.junit.jupiter.api.Test;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.HandlerTypePredicate;
/**
* Test case for api path prefix predicate.
*
* @author guqing
* @date 2022-04-13
*/
public class PathPrefixPredicateTest {
@Test
public void prefixPredicate() {
boolean falseResult = HandlerTypePredicate.forAnnotation(RestController.class)
.and(HandlerTypePredicate.forBasePackage(Application.class.getPackageName()))
.test(getClass());
assertThat(falseResult).isFalse();
boolean result = HandlerTypePredicate.forAnnotation(RestController.class)
.and(HandlerTypePredicate.forBasePackage(Application.class.getPackageName()))
.test(TestController.class);
assertThat(result).isTrue();
}
@RestController("controller-for-test")
@RequestMapping("/test-prefix")
class TestController {
}
@Test
void urlTest() {
URI uri = URI.create("https:///path");
System.out.println(uri);
}
}
| 1,247 | Java | .java | 35 | 30.342857 | 89 | 0.730673 | halo-dev/halo | 33,089 | 9,570 | 340 | GPL-3.0 | 9/4/2024, 7:04:55 PM (Europe/Amsterdam) | false | false | false | false | false | false | false |
1 | ApplicationTests.java | halo-dev_halo/application/src/test/java/run/halo/app/ApplicationTests.java | package run.halo.app;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class ApplicationTests {
@Test
void contextLoads() {
}
}
| 207 | Java | .java | 9 | 20.222222 | 60 | 0.78866 | halo-dev/halo | 33,089 | 9,570 | 340 | GPL-3.0 | 9/4/2024, 7:04:55 PM (Europe/Amsterdam) | false | false | false | false | true | true | true |
2 | XForwardHeaderTest.java | halo-dev_halo/application/src/test/java/run/halo/app/XForwardHeaderTest.java | package run.halo.app;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
import static org.springframework.web.reactive.function.server.RouterFunctions.route;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.test.StepVerifier;
@SpringBootTest(webEnvironment = RANDOM_PORT,
properties = "server.forward-headers-strategy=native")
class XForwardHeaderTest {
@LocalServerPort
int port;
@Test
void shouldGetCorrectProtoFromXForwardHeaders() {
var response = WebClient.create("http://localhost:" + port)
.get().uri("/print-uri")
.header("X-Forwarded-Proto", "https")
.header("X-Forwarded-Host", "halo.run")
.header("X-Forwarded-Port", "6666")
.retrieve()
.toEntity(String.class);
StepVerifier.create(response)
.assertNext(entity -> {
assertEquals(HttpStatus.OK, entity.getStatusCode());
assertEquals("\"https://halo.run:6666/print-uri\"", entity.getBody());
})
.verifyComplete();
}
@TestConfiguration
static class Configuration {
@Bean
RouterFunction<ServerResponse> printUri() {
return route(GET("/print-uri"),
request -> {
var uri = request.exchange().getRequest().getURI();
return ServerResponse.ok().bodyValue(uri);
});
}
}
}
| 2,120 | Java | .java | 48 | 36.770833 | 94 | 0.705085 | halo-dev/halo | 33,089 | 9,570 | 340 | GPL-3.0 | 9/4/2024, 7:04:55 PM (Europe/Amsterdam) | false | false | false | false | false | false | false |
3 | AbstractExtensionTest.java | halo-dev_halo/application/src/test/java/run/halo/app/extension/AbstractExtensionTest.java | package run.halo.app.extension;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class AbstractExtensionTest {
@Test
void groupVersionKind() {
var extension = new AbstractExtension() {
};
extension.setApiVersion("fake.halo.run/v1alpha1");
extension.setKind("Fake");
var gvk = extension.groupVersionKind();
assertEquals(new GroupVersionKind("fake.halo.run", "v1alpha1", "Fake"), gvk);
}
@Test
void testGroupVersionKind() {
var extension = new AbstractExtension() {
};
extension.groupVersionKind(new GroupVersionKind("fake.halo.run", "v1alpha1", "Fake"));
assertEquals("fake.halo.run/v1alpha1", extension.getApiVersion());
assertEquals("Fake", extension.getKind());
}
@Test
void metadata() {
var extension = new AbstractExtension() {
};
Metadata metadata = new Metadata();
metadata.setName("fake");
extension.setMetadata(metadata);
assertEquals(metadata, extension.getMetadata());
}
@Test
void testMetadata() {
var extension = new AbstractExtension() {
};
Metadata metadata = new Metadata();
metadata.setName("fake");
extension.setMetadata(metadata);
assertEquals(metadata, extension.getMetadata());
}
} | 1,392 | Java | .java | 40 | 27.725 | 94 | 0.65399 | halo-dev/halo | 33,089 | 9,570 | 340 | GPL-3.0 | 9/4/2024, 7:04:55 PM (Europe/Amsterdam) | false | false | false | false | false | false | false |
4 | ListResultTest.java | halo-dev_halo/application/src/test/java/run/halo/app/extension/ListResultTest.java | package run.halo.app.extension;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.Test;
class ListResultTest {
@Test
void generateGenericClass() {
var fakeListClass =
ListResult.generateGenericClass(Scheme.buildFromType(FakeExtension.class));
assertTrue(ListResult.class.isAssignableFrom(fakeListClass));
assertSame(FakeExtension.class, ((ParameterizedType) fakeListClass.getGenericSuperclass())
.getActualTypeArguments()[0]);
assertEquals("FakeList", fakeListClass.getSimpleName());
}
@Test
void generateGenericClassForClassParam() {
var fakeListClass = ListResult.generateGenericClass(FakeExtension.class);
assertTrue(ListResult.class.isAssignableFrom(fakeListClass));
assertSame(FakeExtension.class, ((ParameterizedType) fakeListClass.getGenericSuperclass())
.getActualTypeArguments()[0]);
assertEquals("FakeExtensionList", fakeListClass.getSimpleName());
}
@Test
void totalPages() {
var listResult = new ListResult<>(1, 10, 100, List.of());
assertEquals(10, listResult.getTotalPages());
listResult = new ListResult<>(1, 10, 1, List.of());
assertEquals(1, listResult.getTotalPages());
listResult = new ListResult<>(1, 10, 9, List.of());
assertEquals(1, listResult.getTotalPages());
listResult = new ListResult<>(1, 0, 100, List.of());
assertEquals(1, listResult.getTotalPages());
}
@Test
void subListWhenSizeIsZero() {
var list = List.of(1, 2, 3, 4, 5);
assertSubList(list);
list = List.of(1);
assertSubList(list);
}
@Test
void firstTest() {
var listResult = new ListResult<>(List.of());
assertEquals(Optional.empty(), ListResult.first(listResult));
listResult = new ListResult<>(1, 10, 1, List.of("A"));
assertEquals(Optional.of("A"), ListResult.first(listResult));
}
private void assertSubList(List<Integer> list) {
var result = ListResult.subList(list, 0, 0);
assertEquals(list, result);
result = ListResult.subList(list, 0, 1);
assertEquals(list.subList(0, 1), result);
result = ListResult.subList(list, 1, 0);
assertEquals(list, result);
assertEquals(list.subList(0, 1), ListResult.subList(list, -1, 1));
}
} | 2,637 | Java | .java | 61 | 36.196721 | 98 | 0.685938 | halo-dev/halo | 33,089 | 9,570 | 340 | GPL-3.0 | 9/4/2024, 7:04:55 PM (Europe/Amsterdam) | false | false | false | false | false | false | false |
5 | MetadataOperatorTest.java | halo-dev_halo/application/src/test/java/run/halo/app/extension/MetadataOperatorTest.java | package run.halo.app.extension;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static run.halo.app.extension.MetadataOperator.metadataDeepEquals;
import java.time.Instant;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.Test;
class MetadataOperatorTest {
Instant now = Instant.now();
@Test
void testMetadataDeepEqualsWithSameType() {
assertTrue(metadataDeepEquals(null, null));
var left = createFullMetadata();
var right = createFullMetadata();
assertFalse(metadataDeepEquals(left, null));
assertFalse(metadataDeepEquals(null, right));
assertTrue(metadataDeepEquals(left, right));
left.setDeletionTimestamp(null);
assertFalse(metadataDeepEquals(left, right));
right.setDeletionTimestamp(null);
assertTrue(metadataDeepEquals(left, right));
left.setCreationTimestamp(null);
assertFalse(metadataDeepEquals(left, right));
right.setCreationTimestamp(null);
assertTrue(metadataDeepEquals(left, right));
left.setVersion(null);
assertFalse(metadataDeepEquals(left, right));
right.setVersion(null);
assertTrue(metadataDeepEquals(left, right));
left.setAnnotations(null);
assertFalse(metadataDeepEquals(left, right));
right.setAnnotations(null);
assertTrue(metadataDeepEquals(left, right));
left.setLabels(null);
assertFalse(metadataDeepEquals(left, right));
right.setLabels(null);
assertTrue(metadataDeepEquals(left, right));
left.setName(null);
assertFalse(metadataDeepEquals(left, right));
right.setName(null);
assertTrue(metadataDeepEquals(left, right));
left.setFinalizers(null);
assertFalse(metadataDeepEquals(left, right));
right.setFinalizers(null);
assertTrue(metadataDeepEquals(left, right));
}
@Test
void testMetadataDeepEqualsWithDifferentType() {
var mockMetadata = mock(MetadataOperator.class);
when(mockMetadata.getName()).thenReturn("fake-name");
when(mockMetadata.getLabels()).thenReturn(Map.of("fake-label-key", "fake-label-value"));
when(mockMetadata.getAnnotations()).thenReturn(Map.of("fake-anno-key", "fake-anno-value"));
when(mockMetadata.getVersion()).thenReturn(123L);
when(mockMetadata.getCreationTimestamp()).thenReturn(now);
when(mockMetadata.getDeletionTimestamp()).thenReturn(now);
when(mockMetadata.getFinalizers())
.thenReturn(Set.of("fake-finalizer-1", "fake-finalizer-2"));
var metadata = createFullMetadata();
assertTrue(metadataDeepEquals(metadata, mockMetadata));
}
Metadata createFullMetadata() {
var metadata = new Metadata();
metadata.setName("fake-name");
metadata.setLabels(Map.of("fake-label-key", "fake-label-value"));
metadata.setAnnotations(Map.of("fake-anno-key", "fake-anno-value"));
metadata.setVersion(123L);
metadata.setCreationTimestamp(now);
metadata.setDeletionTimestamp(now);
metadata.setFinalizers(Set.of("fake-finalizer-2", "fake-finalizer-1"));
return metadata;
}
} | 3,385 | Java | .java | 75 | 37.64 | 99 | 0.706829 | halo-dev/halo | 33,089 | 9,570 | 340 | GPL-3.0 | 9/4/2024, 7:04:55 PM (Europe/Amsterdam) | false | false | false | false | false | false | false |
6 | UnstructuredTest.java | halo-dev_halo/application/src/test/java/run/halo/app/extension/UnstructuredTest.java | package run.halo.app.extension;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static run.halo.app.extension.MetadataOperator.metadataDeepEquals;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.time.Instant;
import java.util.Map;
import java.util.Set;
import org.json.JSONException;
import org.junit.jupiter.api.Test;
import org.skyscreamer.jsonassert.JSONAssert;
class UnstructuredTest {
ObjectMapper objectMapper = Unstructured.OBJECT_MAPPER;
String extensionJson = """
{
"apiVersion": "fake.halo.run/v1alpha1",
"kind": "Fake",
"metadata": {
"labels": {
"category": "fake",
"default": "true"
},
"name": "fake-extension",
"creationTimestamp": "2011-12-03T10:15:30Z",
"version": 12345,
"finalizers": ["finalizer.1", "finalizer.2"]
}
}
""";
@Test
void shouldSerializeCorrectly() throws JsonProcessingException {
Map extensionMap = objectMapper.readValue(extensionJson, Map.class);
var extension = new Unstructured(extensionMap);
var gotNode = objectMapper.valueToTree(extension);
assertEquals(objectMapper.readTree(extensionJson), gotNode);
}
@Test
void shouldSetCreationTimestamp() throws JsonProcessingException, JSONException {
Map extensionMap = objectMapper.readValue(extensionJson, Map.class);
var extension = new Unstructured(extensionMap);
var beforeChange = objectMapper.writeValueAsString(extension);
var metadata = extension.getMetadata();
metadata.setCreationTimestamp(metadata.getCreationTimestamp());
var afterChange = objectMapper.writeValueAsString(extension);
JSONAssert.assertEquals(beforeChange, afterChange, true);
}
@Test
void shouldDeserializeCorrectly() throws JsonProcessingException, JSONException {
var extension = objectMapper.readValue(extensionJson, Unstructured.class);
var gotJson = objectMapper.writeValueAsString(extension);
JSONAssert.assertEquals(extensionJson, gotJson, true);
}
@Test
void shouldGetExtensionCorrectly() throws JsonProcessingException {
var extension = objectMapper.readValue(extensionJson, Unstructured.class);
assertEquals("fake.halo.run/v1alpha1", extension.getApiVersion());
assertEquals("Fake", extension.getKind());
metadataDeepEquals(createMetadata(), extension.getMetadata());
}
@Test
void shouldSetExtensionCorrectly() {
var extension = createUnstructured();
assertEquals("fake.halo.run/v1alpha1", extension.getApiVersion());
assertEquals("Fake", extension.getKind());
assertTrue(metadataDeepEquals(createMetadata(), extension.getMetadata()));
}
@Test
void shouldBeEqual() {
assertEquals(new Unstructured(), new Unstructured());
assertEquals(createUnstructured(), createUnstructured());
}
@Test
void shouldNotBeEqual() {
var another = createUnstructured();
another.getMetadata().setName("fake-extension-2");
assertNotEquals(createUnstructured(), another);
}
@Test
void shouldGetFinalizersCorrectly() throws JsonProcessingException {
var extension = objectMapper.readValue(extensionJson, Unstructured.class);
assertEquals(Set.of("finalizer.1", "finalizer.2"), extension.getMetadata().getFinalizers());
extension.getMetadata().setFinalizers(Set.of("finalizer.3", "finalizer.4"));
assertEquals(Set.of("finalizer.3", "finalizer.4"), extension.getMetadata().getFinalizers());
}
@Test
void shouldSetLabelsCorrectly() throws JsonProcessingException {
var extension = objectMapper.readValue(extensionJson, Unstructured.class);
assertEquals(Map.of("category", "fake", "default", "true"),
extension.getMetadata().getLabels());
extension.getMetadata().setLabels(Map.of("category", "fake", "default", "false"));
assertEquals(Map.of("category", "fake", "default", "false"),
extension.getMetadata().getLabels());
}
@Test
void shouldSetAnnotationsCorrectly() throws JsonProcessingException {
var extension = objectMapper.readValue(extensionJson, Unstructured.class);
assertNull(extension.getMetadata().getAnnotations());
extension.getMetadata()
.setAnnotations(Map.of("annotation1", "value1", "annotation2", "value2"));
assertEquals(Map.of("annotation1", "value1", "annotation2", "value2"),
extension.getMetadata().getAnnotations());
}
Unstructured createUnstructured() {
var unstructured = new Unstructured();
unstructured.setApiVersion("fake.halo.run/v1alpha1");
unstructured.setKind("Fake");
unstructured.setMetadata(createMetadata());
return unstructured;
}
private Metadata createMetadata() {
var metadata = new Metadata();
metadata.setName("fake-extension");
metadata.setLabels(Map.of("category", "fake", "default", "true"));
metadata.setCreationTimestamp(Instant.parse("2011-12-03T10:15:30Z"));
metadata.setVersion(12345L);
return metadata;
}
}
| 5,606 | Java | .java | 121 | 38.46281 | 100 | 0.695636 | halo-dev/halo | 33,089 | 9,570 | 340 | GPL-3.0 | 9/4/2024, 7:04:55 PM (Europe/Amsterdam) | false | false | false | false | false | false | false |
7 | ExtensionOperatorTest.java | halo-dev_halo/application/src/test/java/run/halo/app/extension/ExtensionOperatorTest.java | package run.halo.app.extension;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.time.Instant;
import org.junit.jupiter.api.Test;
class ExtensionOperatorTest {
@Test
void testIsNotDeleted() {
var ext = mock(ExtensionOperator.class);
var metadata = mock(Metadata.class);
when(metadata.getDeletionTimestamp()).thenReturn(null);
when(ext.getMetadata()).thenReturn(metadata);
assertTrue(ExtensionOperator.isNotDeleted().test(ext));
when(metadata.getDeletionTimestamp()).thenReturn(Instant.now());
assertFalse(ExtensionOperator.isNotDeleted().test(ext));
}
@Test
void testIsDeleted() {
var ext = mock(ExtensionOperator.class);
when(ext.getMetadata()).thenReturn(null);
assertFalse(ExtensionOperator.isDeleted(ext));
var metadata = mock(Metadata.class);
when(ext.getMetadata()).thenReturn(metadata);
when(metadata.getDeletionTimestamp()).thenReturn(null);
assertFalse(ExtensionOperator.isDeleted(ext));
when(metadata.getDeletionTimestamp()).thenReturn(Instant.now());
assertTrue(ExtensionOperator.isDeleted(ext));
}
} | 1,335 | Java | .java | 31 | 36.870968 | 72 | 0.72973 | halo-dev/halo | 33,089 | 9,570 | 340 | GPL-3.0 | 9/4/2024, 7:04:55 PM (Europe/Amsterdam) | false | false | false | false | false | false | false |
8 | ExtensionStoreUtilTest.java | halo-dev_halo/application/src/test/java/run/halo/app/extension/ExtensionStoreUtilTest.java | package run.halo.app.extension;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class ExtensionStoreUtilTest {
Scheme scheme;
Scheme grouplessScheme;
@BeforeEach
void setUp() {
scheme = new Scheme(FakeExtension.class,
new GroupVersionKind("fake.halo.run", "v1alpha1", "Fake"),
"fakes",
"fake",
new ObjectNode(null));
grouplessScheme = new Scheme(FakeExtension.class,
new GroupVersionKind("", "v1alpha1", "Fake"),
"fakes",
"fake",
new ObjectNode(null));
}
@Test
void buildStoreNamePrefix() {
var prefix = ExtensionStoreUtil.buildStoreNamePrefix(scheme);
assertEquals("/registry/fake.halo.run/fakes", prefix);
prefix = ExtensionStoreUtil.buildStoreNamePrefix(grouplessScheme);
assertEquals("/registry/fakes", prefix);
}
@Test
void buildStoreName() {
var storeName = ExtensionStoreUtil.buildStoreName(scheme, "fake-name");
assertEquals("/registry/fake.halo.run/fakes/fake-name", storeName);
storeName = ExtensionStoreUtil.buildStoreName(grouplessScheme, "fake-name");
assertEquals("/registry/fakes/fake-name", storeName);
}
} | 1,397 | Java | .java | 36 | 31.416667 | 84 | 0.679497 | halo-dev/halo | 33,089 | 9,570 | 340 | GPL-3.0 | 9/4/2024, 7:04:55 PM (Europe/Amsterdam) | false | false | false | false | false | false | false |
9 | DefaultSchemeWatcherManagerTest.java | halo-dev_halo/application/src/test/java/run/halo/app/extension/DefaultSchemeWatcherManagerTest.java | package run.halo.app.extension;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;
import java.util.Collections;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import run.halo.app.extension.SchemeWatcherManager.SchemeWatcher;
class DefaultSchemeWatcherManagerTest {
DefaultSchemeWatcherManager watcherManager;
@BeforeEach
void setUp() {
watcherManager = new DefaultSchemeWatcherManager();
}
@Test
void shouldThrowExceptionWhenRegisterNullWatcher() {
assertThrows(IllegalArgumentException.class, () -> watcherManager.register(null));
}
@Test
void shouldThrowExceptionWhenUnregisterNullWatcher() {
assertThrows(IllegalArgumentException.class, () -> watcherManager.unregister(null));
}
@Test
void shouldRegisterSuccessfully() {
var watcher = mock(SchemeWatcher.class);
watcherManager.register(watcher);
assertEquals(watcherManager.watchers(), List.of(watcher));
}
@Test
void shouldUnregisterSuccessfully() {
var watcher = mock(SchemeWatcher.class);
watcherManager.register(watcher);
assertEquals(List.of(watcher), watcherManager.watchers());
watcherManager.unregister(watcher);
assertEquals(Collections.emptyList(), watcherManager.watchers());
}
@Test
void shouldReturnCopyOfWatchers() {
var firstWatcher = mock(SchemeWatcher.class);
var secondWatcher = mock(SchemeWatcher.class);
watcherManager.register(firstWatcher);
var watchers = watcherManager.watchers();
watchers.forEach(watcher -> watcherManager.register(secondWatcher));
}
} | 1,811 | Java | .java | 46 | 33.673913 | 92 | 0.74729 | halo-dev/halo | 33,089 | 9,570 | 340 | GPL-3.0 | 9/4/2024, 7:04:55 PM (Europe/Amsterdam) | false | false | false | false | false | false | false |
10 | FakeExtension.java | halo-dev_halo/application/src/test/java/run/halo/app/extension/FakeExtension.java | package run.halo.app.extension;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
@GVK(group = "fake.halo.run",
version = "v1alpha1",
kind = "Fake",
plural = "fakes",
singular = "fake")
@Data
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
public class FakeExtension extends AbstractExtension {
private FakeStatus status = new FakeStatus();
public static FakeExtension createFake(String name) {
var metadata = new Metadata();
metadata.setName(name);
var fake = new FakeExtension();
fake.setMetadata(metadata);
return fake;
}
@Data
public static class FakeStatus {
private String state;
}
}
| 727 | Java | .java | 26 | 23.384615 | 57 | 0.698276 | halo-dev/halo | 33,089 | 9,570 | 340 | GPL-3.0 | 9/4/2024, 7:04:55 PM (Europe/Amsterdam) | false | false | false | false | false | false | false |
11 | GroupVersionTest.java | halo-dev_halo/application/src/test/java/run/halo/app/extension/GroupVersionTest.java | package run.halo.app.extension;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
class GroupVersionTest {
@Test
void shouldThrowIllegalArgumentExceptionWhenAPIVersionIsIllegal() {
assertThrows(IllegalArgumentException.class, () -> GroupVersion.parseAPIVersion(null),
"apiVersion is null");
assertThrows(IllegalArgumentException.class, () -> GroupVersion.parseAPIVersion(""),
"apiVersion is empty");
assertThrows(IllegalArgumentException.class, () -> GroupVersion.parseAPIVersion(" "),
"apiVersion is blank");
assertThrows(IllegalArgumentException.class, () -> GroupVersion.parseAPIVersion("a/b/c"),
"apiVersion contains more than 1 '/'");
}
@Test
void shouldReturnGroupVersionCorrectly() {
assertEquals(new GroupVersion("", "v1"), GroupVersion.parseAPIVersion("v1"),
"only contains version");
assertEquals(new GroupVersion("core.halo.run", "v1"),
GroupVersion.parseAPIVersion("core.halo.run/v1"), "only contains version");
}
} | 1,186 | Java | .java | 24 | 42.25 | 97 | 0.70639 | halo-dev/halo | 33,089 | 9,570 | 340 | GPL-3.0 | 9/4/2024, 7:04:55 PM (Europe/Amsterdam) | false | false | false | false | false | false | false |
12 | JsonExtensionConverterTest.java | halo-dev_halo/application/src/test/java/run/halo/app/extension/JsonExtensionConverterTest.java | package run.halo.app.extension;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.Locale;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import run.halo.app.extension.exception.ExtensionConvertException;
import run.halo.app.extension.exception.SchemaViolationException;
import run.halo.app.extension.index.IndexSpecRegistry;
import run.halo.app.extension.store.ExtensionStore;
class JsonExtensionConverterTest {
JSONExtensionConverter converter;
ObjectMapper objectMapper;
Locale localeDefault;
@BeforeEach
void setUp() {
localeDefault = Locale.getDefault();
Locale.setDefault(Locale.ENGLISH);
var indexSpecRegistry = mock(IndexSpecRegistry.class);
DefaultSchemeManager schemeManager = new DefaultSchemeManager(indexSpecRegistry, null);
converter = new JSONExtensionConverter(schemeManager);
objectMapper = converter.getObjectMapper();
schemeManager.register(FakeExtension.class);
}
@AfterEach
void cleanUp() {
Locale.setDefault(localeDefault);
}
@Test
void convertTo() throws IOException {
var fake = createFakeExtension("fake", 10L);
var extensionStore = converter.convertTo(fake);
assertEquals("/registry/fake.halo.run/fakes/fake", extensionStore.getName());
assertEquals(10L, extensionStore.getVersion());
assertEquals(fake, objectMapper.readValue(extensionStore.getData(), FakeExtension.class));
}
@Test
void convertFrom() throws JsonProcessingException {
var fake = createFakeExtension("fake", 20L);
var store = new ExtensionStore();
store.setName("/registry/fake.halo.run/fakes/fake");
store.setVersion(20L);
store.setData(objectMapper.writeValueAsBytes(fake));
FakeExtension gotFake = converter.convertFrom(FakeExtension.class, store);
assertEquals(fake, gotFake);
}
@Test
void shouldThrowConvertExceptionWhenDataIsInvalid() {
var store = new ExtensionStore();
store.setName("/registry/fake.halo.run/fakes/fake");
store.setVersion(20L);
store.setData("{".getBytes());
assertThrows(ExtensionConvertException.class,
() -> converter.convertFrom(FakeExtension.class, store));
}
@Test
void shouldThrowSchemaViolationExceptionWhenNameNotSet() {
var fake = new FakeExtension();
Metadata metadata = new Metadata();
fake.setMetadata(metadata);
fake.setApiVersion("fake.halo.run/v1alpha1");
fake.setKind("Fake");
var error = assertThrows(SchemaViolationException.class, () -> converter.convertTo(fake));
assertEquals(1, error.getErrors().size());
var result = error.getErrors().items().get(0);
assertEquals(1026, result.code());
assertEquals("Field 'name' is required.", result.message());
}
FakeExtension createFakeExtension(String name, Long version) {
var fake = new FakeExtension();
fake.groupVersionKind(new GroupVersionKind("fake.halo.run", "v1alpha1", "Fake"));
Metadata metadata = new Metadata();
metadata.setName(name);
metadata.setVersion(version);
fake.setMetadata(metadata);
return fake;
}
} | 3,599 | Java | .java | 83 | 36.819277 | 98 | 0.72254 | halo-dev/halo | 33,089 | 9,570 | 340 | GPL-3.0 | 9/4/2024, 7:04:55 PM (Europe/Amsterdam) | false | false | false | false | false | false | false |
13 | ComparatorsTest.java | halo-dev_halo/application/src/test/java/run/halo/app/extension/ComparatorsTest.java | package run.halo.app.extension;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
class ComparatorsTest {
@Nested
class CompareCreationTimestamp {
FakeExtension createFake(String name, Instant creationTimestamp) {
var metadata = new Metadata();
metadata.setName(name);
metadata.setCreationTimestamp(creationTimestamp);
var fake = new FakeExtension();
fake.setMetadata(metadata);
return fake;
}
@Test
void desc() {
var comparator = Comparators.compareCreationTimestamp(false);
var now = Instant.now();
var before = now.minusMillis(1);
var after = now.plusMillis(1);
var fakeNow = createFake("now", now);
var fakeBefore = createFake("before", before);
var fakeAfter = createFake("after", after);
var sortedFakes = new ArrayList<>(List.of(fakeNow, fakeAfter, fakeBefore));
sortedFakes.sort(comparator);
assertEquals(List.of(fakeAfter, fakeNow, fakeBefore), sortedFakes);
}
@Test
void asc() {
var comparator = Comparators.compareCreationTimestamp(true);
var now = Instant.now();
var before = now.minusMillis(1);
var after = now.plusMillis(1);
var fakeNow = createFake("now", now);
var fakeBefore = createFake("before", before);
var fakeAfter = createFake("after", after);
var sortedFakes = new ArrayList<>(List.of(fakeNow, fakeAfter, fakeBefore));
sortedFakes.sort(comparator);
assertEquals(List.of(fakeBefore, fakeNow, fakeAfter), sortedFakes);
}
}
@Nested
class CompareName {
FakeExtension createFake(String name) {
var metadata = new Metadata();
metadata.setName(name);
var fake = new FakeExtension();
fake.setMetadata(metadata);
return fake;
}
@Test
void desc() {
var comparator = Comparators.compareName(false);
var fake01 = createFake("fake01");
var fake02 = createFake("fake02");
var fake03 = createFake("fake03");
var sortedFakes = new ArrayList<>(List.of(fake02, fake01, fake03));
sortedFakes.sort(comparator);
assertEquals(List.of(fake03, fake02, fake01), sortedFakes);
}
@Test
void asc() {
var comparator = Comparators.compareName(true);
var fake01 = createFake("fake01");
var fake02 = createFake("fake02");
var fake03 = createFake("fake03");
var sortedFakes = new ArrayList<>(List.of(fake02, fake03, fake01));
sortedFakes.sort(comparator);
assertEquals(List.of(fake01, fake02, fake03), sortedFakes);
}
}
} | 3,086 | Java | .java | 76 | 30.236842 | 87 | 0.606689 | halo-dev/halo | 33,089 | 9,570 | 340 | GPL-3.0 | 9/4/2024, 7:04:55 PM (Europe/Amsterdam) | false | false | false | false | false | false | false |
14 | RefTest.java | halo-dev_halo/application/src/test/java/run/halo/app/extension/RefTest.java | package run.halo.app.extension;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static run.halo.app.extension.GroupVersionKind.fromAPIVersionAndKind;
import static run.halo.app.extension.GroupVersionKind.fromExtension;
import org.junit.jupiter.api.Test;
class RefTest {
@Test
void shouldHasSameGroupAndKind() {
FakeExtension fake = new FakeExtension();
Metadata metadata = new Metadata();
metadata.setName("fake");
fake.setMetadata(metadata);
assertTrue(Ref.groupKindEquals(Ref.of(fake), fromExtension(fake.getClass())));
// has different version
assertTrue(Ref.groupKindEquals(Ref.of(fake),
fromAPIVersionAndKind("fake.halo.run/v11111111111", "Fake")));
assertFalse(Ref.groupKindEquals(Ref.of(fake),
fromAPIVersionAndKind("fake.halo.run/v1alpha1", "NotFake")));
}
} | 948 | Java | .java | 21 | 39.238095 | 86 | 0.737013 | halo-dev/halo | 33,089 | 9,570 | 340 | GPL-3.0 | 9/4/2024, 7:04:55 PM (Europe/Amsterdam) | false | false | false | false | false | false | false |
15 | GroupVersionKindTest.java | halo-dev_halo/application/src/test/java/run/halo/app/extension/GroupVersionKindTest.java | package run.halo.app.extension;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static run.halo.app.extension.GroupVersionKind.fromAPIVersionAndKind;
import java.util.List;
import org.junit.jupiter.api.Test;
class GroupVersionKindTest {
@Test
void testFromApiVersionAndKind() {
record TestCase(String apiVersion, String kind, GroupVersionKind expected,
Class<? extends Throwable> exception) {
}
List.of(
new TestCase("v1alpha1", "Fake", new GroupVersionKind("", "v1alpha1", "Fake"), null),
new TestCase("fake.halo.run/v1alpha1", "Fake",
new GroupVersionKind("fake.halo.run", "v1alpha1", "Fake"), null),
new TestCase("", "", null, IllegalArgumentException.class),
new TestCase("", "Fake", null, IllegalArgumentException.class),
new TestCase("v1alpha1", "", null, IllegalArgumentException.class),
new TestCase("fake.halo.run/v1alpha1/v1alpha2", "Fake", null,
IllegalArgumentException.class)
).forEach(testCase -> {
if (testCase.exception != null) {
assertThrows(testCase.exception, () -> {
fromAPIVersionAndKind(testCase.apiVersion, testCase.kind);
});
} else {
var got = fromAPIVersionAndKind(testCase.apiVersion, testCase.kind);
assertEquals(testCase.expected, got);
}
});
}
@Test
void testHasGroup() {
record TestCase(GroupVersionKind gvk, boolean hasGroup) {
}
List.of(
new TestCase(new GroupVersionKind("", "v1alpha1", "Fake"), false),
new TestCase(new GroupVersionKind("fake.halo.run", "v1alpha1", "Fake"), true)
).forEach(testCase -> assertEquals(testCase.hasGroup, testCase.gvk.hasGroup()));
}
@Test
void testGroupKind() {
record TestCase(GroupVersionKind gvk, GroupKind gk) {
}
List.of(
new TestCase(new GroupVersionKind("", "v1alpha1", "Fake"), new GroupKind("", "Fake")),
new TestCase(new GroupVersionKind("fake.halo.run", "v1alpha1", "Fake"),
new GroupKind("fake.halo.run", "Fake"))
).forEach(testCase -> {
assertEquals(testCase.gk, testCase.gvk.groupKind());
});
}
@Test
void testGroupVersion() {
record TestCase(GroupVersionKind gvk, GroupVersion gv) {
}
List.of(
new TestCase(new GroupVersionKind("", "v1alpha1", "Fake"),
new GroupVersion("", "v1alpha1")),
new TestCase(new GroupVersionKind("fake.halo.run", "v1alpha1", "Fake"),
new GroupVersion("fake.halo.run", "v1alpha1"))
).forEach(testCase -> {
assertEquals(testCase.gv, testCase.gvk.groupVersion());
});
}
@Test
void fromExtension() {
GroupVersionKind groupVersionKind = GroupVersionKind.fromExtension(FakeExtension.class);
assertEquals("fake.halo.run", groupVersionKind.group());
assertEquals("v1alpha1", groupVersionKind.version());
assertEquals("Fake", groupVersionKind.kind());
}
} | 3,284 | Java | .java | 74 | 34.621622 | 98 | 0.621326 | halo-dev/halo | 33,089 | 9,570 | 340 | GPL-3.0 | 9/4/2024, 7:04:55 PM (Europe/Amsterdam) | false | false | false | false | false | false | false |
16 | DefaultSchemeManagerTest.java | halo-dev_halo/application/src/test/java/run/halo/app/extension/DefaultSchemeManagerTest.java | package run.halo.app.extension;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import run.halo.app.extension.SchemeWatcherManager.SchemeRegistered;
import run.halo.app.extension.SchemeWatcherManager.SchemeUnregistered;
import run.halo.app.extension.SchemeWatcherManager.SchemeWatcher;
import run.halo.app.extension.exception.SchemeNotFoundException;
import run.halo.app.extension.index.IndexSpecRegistry;
@ExtendWith(MockitoExtension.class)
class DefaultSchemeManagerTest {
@Mock
private IndexSpecRegistry indexSpecRegistry;
@Mock
SchemeWatcherManager watcherManager;
@InjectMocks
DefaultSchemeManager schemeManager;
@Test
void shouldThrowExceptionWhenNoGvkAnnotation() {
class WithoutGvkExtension extends AbstractExtension {
}
assertThrows(IllegalArgumentException.class,
() -> schemeManager.register(WithoutGvkExtension.class));
}
@Test
void shouldGetNothingWhenUnregistered() {
final var gvk = new GroupVersionKind("fake.halo.run", "v1alpha1", "Fake");
var scheme = schemeManager.fetch(gvk);
assertFalse(scheme.isPresent());
assertThrows(SchemeNotFoundException.class, () -> schemeManager.get(gvk));
assertThrows(SchemeNotFoundException.class, () -> schemeManager.get(FakeExtension.class));
assertThrows(SchemeNotFoundException.class, () -> schemeManager.get(new FakeExtension()));
}
@Test
void shouldGetSchemeWhenRegistered() {
schemeManager.register(FakeExtension.class);
final var gvk = new GroupVersionKind("fake.halo.run", "v1alpha1", "Fake");
var scheme = schemeManager.fetch(gvk);
assertTrue(scheme.isPresent());
assertEquals(gvk, schemeManager.get(gvk).groupVersionKind());
assertEquals(gvk, schemeManager.get(FakeExtension.class).groupVersionKind());
assertEquals(gvk, schemeManager.get(new FakeExtension()).groupVersionKind());
}
@Test
void shouldUnregisterSuccessfully() {
schemeManager.register(FakeExtension.class);
Scheme scheme = schemeManager.get(FakeExtension.class);
assertNotNull(scheme);
schemeManager.unregister(scheme);
assertThrows(SchemeNotFoundException.class, () -> schemeManager.get(FakeExtension.class));
}
@Test
void shouldTriggerOnChangeOnlyOnceWhenRegisterTwice() {
final var watcher = mock(SchemeWatcher.class);
when(watcherManager.watchers()).thenReturn(List.of(watcher));
schemeManager.register(FakeExtension.class);
verify(watcherManager, times(1)).watchers();
verify(watcher, times(1)).onChange(isA(SchemeRegistered.class));
schemeManager.register(FakeExtension.class);
verify(watcherManager, times(1)).watchers();
verify(watcher, times(1)).onChange(isA(SchemeRegistered.class));
verify(indexSpecRegistry).indexFor(any(Scheme.class));
}
@Test
void shouldTriggerOnChangeOnlyOnceWhenUnregisterTwice() {
final var watcher = mock(SchemeWatcher.class);
when(watcherManager.watchers()).thenReturn(List.of(watcher));
schemeManager.register(FakeExtension.class);
var scheme = schemeManager.get(FakeExtension.class);
schemeManager.unregister(scheme);
verify(watcherManager, times(2)).watchers();
verify(watcher, times(1)).onChange(isA(SchemeUnregistered.class));
schemeManager.unregister(scheme);
verify(watcherManager, times(2)).watchers();
verify(watcher, times(1)).onChange(isA(SchemeUnregistered.class));
verify(indexSpecRegistry).indexFor(any(Scheme.class));
}
@Test
void getSizeOfSchemes() {
assertEquals(0, schemeManager.size());
schemeManager.register(FakeExtension.class);
assertEquals(1, schemeManager.size());
schemeManager.unregister(schemeManager.get(FakeExtension.class));
assertEquals(0, schemeManager.size());
}
@Test
void shouldReturnCopyOnWriteList() {
schemeManager.register(FakeExtension.class);
var schemes = schemeManager.schemes();
schemes.forEach(scheme -> {
// make sure concurrent modification won't happen
schemeManager.register(FooExtension.class);
});
}
@GVK(group = "fake.halo.run", version = "v1alpha1", kind = "Foo",
plural = "foos", singular = "foo")
static class FooExtension extends AbstractExtension {
}
}
| 5,207 | Java | .java | 113 | 39.743363 | 98 | 0.739886 | halo-dev/halo | 33,089 | 9,570 | 340 | GPL-3.0 | 9/4/2024, 7:04:55 PM (Europe/Amsterdam) | false | false | false | false | false | false | false |
17 | ConfigMapTest.java | halo-dev_halo/application/src/test/java/run/halo/app/extension/ConfigMapTest.java | package run.halo.app.extension;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.doNothing;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.security.util.InMemoryResource;
import run.halo.app.infra.utils.YamlUnstructuredLoader;
/**
* Tests for {@link ConfigMap}.
*
* @author guqing
* @since 2.0.0
*/
@ExtendWith(MockitoExtension.class)
class ConfigMapTest {
@Mock
ExtensionClient extensionClient;
@Test
void configMapTest() {
ArgumentCaptor<ConfigMap> argumentCaptor = ArgumentCaptor.forClass(ConfigMap.class);
doNothing().when(extensionClient).create(argumentCaptor.capture());
ConfigMap configMap = new ConfigMap();
Metadata metadata = new Metadata();
metadata.setName("test-configmap");
configMap.setMetadata(metadata);
Map<String, String> data = Map.of("k1", "v1", "k2", "v2", "k3", "v3");
configMap.setData(data);
extensionClient.create(configMap);
ConfigMap value = argumentCaptor.getValue();
assertThat(value).isNotNull();
assertThat(value.getData()).isEqualTo(data);
}
@Test
void putDataItem() {
ConfigMap configMap = new ConfigMap();
configMap.putDataItem("k1", "v1")
.putDataItem("k2", "v2")
.putDataItem("k3", "v3");
assertThat(configMap.getData()).isNotNull();
assertThat(configMap.getData()).hasSize(3);
assertThat(configMap.getData()).isEqualTo(
Map.of("k1", "v1", "k2", "v2", "k3", "v3"));
}
@Test
void equalsTest() {
ConfigMap configMapA = new ConfigMap();
Metadata metadataA = new Metadata();
metadataA.setName("test-configmap");
configMapA.setMetadata(metadataA);
configMapA.putDataItem("k1", "v1");
ConfigMap configMapB = new ConfigMap();
Metadata metadataB = new Metadata();
metadataB.setName("test-configmap");
configMapB.setMetadata(metadataB);
configMapB.putDataItem("k1", "v1");
assertThat(configMapA).isEqualTo(configMapB);
configMapB.getMetadata().setName("test-configmap-2");
assertThat(configMapA).isNotEqualTo(configMapB);
}
@Test
void yamlTest() {
String configMapYaml = """
apiVersion: v1alpha1
kind: ConfigMap
metadata:
name: test-configmap
data:
k1: v1
k2: v2
k3: v3
""";
List<Unstructured> unstructureds =
new YamlUnstructuredLoader(new InMemoryResource(configMapYaml)).load();
assertThat(unstructureds).hasSize(1);
Unstructured unstructured = unstructureds.get(0);
ConfigMap configMap =
Unstructured.OBJECT_MAPPER.convertValue(unstructured, ConfigMap.class);
assertThat(configMap.getData()).isEqualTo(Map.of("k1", "v1", "k2", "v2", "k3", "v3"));
assertThat(configMap.getMetadata().getName()).isEqualTo("test-configmap");
assertThat(configMap.getApiVersion()).isEqualTo("v1alpha1");
assertThat(configMap.getKind()).isEqualTo("ConfigMap");
}
} | 3,436 | Java | .java | 88 | 31.284091 | 94 | 0.655069 | halo-dev/halo | 33,089 | 9,570 | 340 | GPL-3.0 | 9/4/2024, 7:04:55 PM (Europe/Amsterdam) | false | false | false | false | false | false | false |
18 | SchemeTest.java | halo-dev_halo/application/src/test/java/run/halo/app/extension/SchemeTest.java | package run.halo.app.extension;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.junit.jupiter.api.Test;
class SchemeTest {
@Test
void requiredFieldTest() {
assertThrows(IllegalArgumentException.class,
() -> new Scheme(null, new GroupVersionKind("", "v1alpha1", ""), "", "", null));
assertThrows(IllegalArgumentException.class,
() -> new Scheme(FakeExtension.class, new GroupVersionKind("", "", ""), "", "",
null));
assertThrows(IllegalArgumentException.class,
() -> new Scheme(FakeExtension.class, new GroupVersionKind("", "v1alpha1", ""), "",
"", null));
assertThrows(IllegalArgumentException.class,
() -> new Scheme(FakeExtension.class, new GroupVersionKind("", "v1alpha1", "Fake"), "",
"", null));
assertThrows(IllegalArgumentException.class,
() -> new Scheme(FakeExtension.class, new GroupVersionKind("", "v1alpha1", "Fake"),
"fakes", "", null));
assertThrows(IllegalArgumentException.class, () -> {
new Scheme(FakeExtension.class, new GroupVersionKind("", "v1alpha1", "Fake"), "fakes",
"fake", null);
});
new Scheme(FakeExtension.class, new GroupVersionKind("", "v1alpha1", "Fake"), "fakes",
"fake", new ObjectNode(null));
}
@Test
void shouldThrowExceptionWhenTypeHasNoGvkAnno() {
class NoGvkExtension extends AbstractExtension {
}
assertThrows(IllegalArgumentException.class,
() -> Scheme.getGvkFromType(NoGvkExtension.class));
assertThrows(IllegalArgumentException.class,
() -> Scheme.buildFromType(NoGvkExtension.class));
}
@Test
void shouldGetGvkFromTypeWithGvkAnno() {
var gvk = Scheme.getGvkFromType(FakeExtension.class);
assertEquals("fake.halo.run", gvk.group());
assertEquals("v1alpha1", gvk.version());
assertEquals("Fake", gvk.kind());
assertEquals("fake", gvk.singular());
assertEquals("fakes", gvk.plural());
}
@Test
void shouldCreateSchemeSuccessfully() {
var scheme = Scheme.buildFromType(FakeExtension.class);
assertEquals(new GroupVersionKind("fake.halo.run", "v1alpha1", "Fake"),
scheme.groupVersionKind());
assertEquals("fake", scheme.singular());
assertEquals("fakes", scheme.plural());
assertNotNull(scheme.openApiSchema());
assertEquals(FakeExtension.class, scheme.type());
}
@Test
void equalsAndHashCodeTest() {
var scheme1 = Scheme.buildFromType(FakeExtension.class);
var scheme2 = Scheme.buildFromType(FakeExtension.class);
assertEquals(scheme1, scheme2);
assertEquals(scheme1.hashCode(), scheme2.hashCode());
// openApiSchema is not included in equals and hashCode.
var scheme3 = new Scheme(FakeExtension.class, scheme1.groupVersionKind(),
scheme1.plural(), scheme1.singular(), JsonNodeFactory.instance.objectNode());
assertEquals(scheme1, scheme3);
// singular and plural are not included in equals and hashCode.
var scheme4 = new Scheme(FakeExtension.class, scheme1.groupVersionKind(),
scheme1.plural(), "other", scheme1.openApiSchema());
assertEquals(scheme1, scheme4);
// plural is not included in equals and hashCode.
var scheme5 = new Scheme(FakeExtension.class, scheme1.groupVersionKind(),
"other", scheme1.singular(), scheme1.openApiSchema());
assertEquals(scheme1, scheme5);
// type is not included in equals and hashCode.
var scheme6 = new Scheme(FakeExtension.class, scheme1.groupVersionKind(),
scheme1.plural(), scheme1.singular(), scheme1.openApiSchema());
assertEquals(scheme1, scheme6);
// groupVersionKind is included in equals and hashCode.
var scheme7 = new Scheme(FakeExtension.class,
new GroupVersionKind("other.halo.run", "v1alpha1", "Fake"),
scheme1.plural(), scheme1.singular(), scheme1.openApiSchema());
assertNotEquals(scheme1, scheme7);
scheme7 = new Scheme(FakeExtension.class,
new GroupVersionKind("fake.halo.run", "v1alpha2", "Fake"),
scheme1.plural(), scheme1.singular(), scheme1.openApiSchema());
assertNotEquals(scheme1, scheme7);
scheme7 = new Scheme(FakeExtension.class,
new GroupVersionKind("fake.halo.run", "v1alpha1", "Other"),
scheme1.plural(), scheme1.singular(), scheme1.openApiSchema());
assertNotEquals(scheme1, scheme7);
}
} | 4,997 | Java | .java | 97 | 42.556701 | 99 | 0.665029 | halo-dev/halo | 33,089 | 9,570 | 340 | GPL-3.0 | 9/4/2024, 7:04:55 PM (Europe/Amsterdam) | false | false | false | false | false | false | false |
19 | JsonExtensionTest.java | halo-dev_halo/application/src/test/java/run/halo/app/extension/JsonExtensionTest.java | package run.halo.app.extension;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fasterxml.jackson.databind.node.TextNode;
import org.json.JSONException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.skyscreamer.jsonassert.JSONAssert;
class JsonExtensionTest {
ObjectMapper objectMapper;
@BeforeEach
void setUp() {
objectMapper = JsonMapper.builder().build();
}
@Test
void serializeEmptyExt() throws JsonProcessingException, JSONException {
var ext = new JsonExtension(objectMapper);
var json = objectMapper.writeValueAsString(ext);
JSONAssert.assertEquals("{}", json, true);
}
@Test
void serializeExt() throws JsonProcessingException, JSONException {
var ext = new JsonExtension(objectMapper);
ext.setApiVersion("fake.halo.run/v1alpha");
ext.setKind("Fake");
var metadata = ext.getMetadataOrCreate();
metadata.setName("fake-name");
ext.getInternal().set("data", TextNode.valueOf("halo"));
JSONAssert.assertEquals("""
{
"apiVersion": "fake.halo.run/v1alpha",
"kind": "Fake",
"metadata": {
"name": "fake-name"
},
"data": "halo"
}""", objectMapper.writeValueAsString(ext), true);
}
@Test
void deserialize() throws JsonProcessingException {
var json = """
{
"apiVersion": "fake.halo.run/v1alpha1",
"kind": "Fake",
"metadata": {
"name": "faker"
},
"otherProperty": "otherPropertyValue"
}""";
var ext = objectMapper.readValue(json, JsonExtension.class);
assertEquals("fake.halo.run/v1alpha1", ext.getApiVersion());
assertEquals("Fake", ext.getKind());
assertNotNull(ext.getMetadata());
assertEquals("faker", ext.getMetadata().getName());
assertNull(ext.getMetadata().getVersion());
assertNull(ext.getMetadata().getFinalizers());
assertNull(ext.getMetadata().getAnnotations());
assertNull(ext.getMetadata().getLabels());
assertNull(ext.getMetadata().getGenerateName());
assertNull(ext.getMetadata().getCreationTimestamp());
assertNull(ext.getMetadata().getDeletionTimestamp());
assertEquals("otherPropertyValue", ext.getInternal().get("otherProperty").asText());
}
} | 2,795 | Java | .java | 68 | 33 | 92 | 0.660162 | halo-dev/halo | 33,089 | 9,570 | 340 | GPL-3.0 | 9/4/2024, 7:04:55 PM (Europe/Amsterdam) | false | false | false | false | false | false | false |
20 | ReactiveExtensionClientTest.java | halo-dev_halo/application/src/test/java/run/halo/app/extension/ReactiveExtensionClientTest.java | package run.halo.app.extension;
import static java.util.Collections.emptyList;
import static java.util.Collections.reverseOrder;
import static java.util.Comparator.comparing;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.assertArg;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.ArgumentMatchers.same;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static run.halo.app.extension.GroupVersionKind.fromAPIVersionAndKind;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.transaction.ReactiveTransactionManager;
import org.springframework.transaction.reactive.TransactionalOperator;
import reactor.core.Exceptions;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import run.halo.app.extension.exception.SchemeNotFoundException;
import run.halo.app.extension.index.Indexer;
import run.halo.app.extension.index.IndexerFactory;
import run.halo.app.extension.store.ExtensionStore;
import run.halo.app.extension.store.ReactiveExtensionStoreClient;
@ExtendWith(MockitoExtension.class)
class ReactiveExtensionClientTest {
static final Scheme fakeScheme = Scheme.buildFromType(FakeExtension.class);
@Mock
ReactiveExtensionStoreClient storeClient;
@Mock
ExtensionConverter converter;
@Mock
SchemeManager schemeManager;
@Mock
IndexerFactory indexerFactory;
@Mock
ReactiveTransactionManager reactiveTransactionManager;
@Spy
ObjectMapper objectMapper = JsonMapper.builder()
.addModule(new JavaTimeModule())
.build();
@InjectMocks
ReactiveExtensionClientImpl client;
@BeforeEach
void setUp() {
lenient().when(schemeManager.get(eq(FakeExtension.class)))
.thenReturn(fakeScheme);
lenient().when(schemeManager.get(eq(fakeScheme.groupVersionKind()))).thenReturn(fakeScheme);
var transactionalOperator = mock(TransactionalOperator.class);
client.setTransactionalOperator(transactionalOperator);
lenient().when(transactionalOperator.transactional(any(Mono.class)))
.thenAnswer(invocation -> invocation.getArgument(0));
}
FakeExtension createFakeExtension(String name, Long version) {
var fake = new FakeExtension();
var metadata = new Metadata();
metadata.setName(name);
metadata.setVersion(version);
fake.setMetadata(metadata);
fake.setApiVersion("fake.halo.run/v1alpha1");
fake.setKind("Fake");
return fake;
}
ExtensionStore createExtensionStore(String name) {
return createExtensionStore(name, null);
}
ExtensionStore createExtensionStore(String name, Long version) {
var extensionStore = new ExtensionStore();
extensionStore.setName(name);
extensionStore.setVersion(version);
return extensionStore;
}
Unstructured createUnstructured() throws JsonProcessingException {
String extensionJson = """
{
"apiVersion": "fake.halo.run/v1alpha1",
"kind": "Fake",
"metadata": {
"labels": {
"category": "fake",
"default": "true"
},
"name": "fake",
"creationTimestamp": "2011-12-03T10:15:30Z",
"version": 12345
}
}
""";
return Unstructured.OBJECT_MAPPER.readValue(extensionJson, Unstructured.class);
}
@Test
void shouldThrowSchemeNotFoundExceptionWhenSchemeNotRegistered() {
class UnRegisteredExtension extends AbstractExtension {
}
when(schemeManager.get(eq(UnRegisteredExtension.class)))
.thenThrow(SchemeNotFoundException.class);
when(schemeManager.get(isA(GroupVersionKind.class)))
.thenThrow(SchemeNotFoundException.class);
assertThrows(SchemeNotFoundException.class,
() -> client.list(UnRegisteredExtension.class, null,
null));
assertThrows(SchemeNotFoundException.class,
() -> client.list(UnRegisteredExtension.class, null, null, 0, 10));
assertThrows(SchemeNotFoundException.class,
() -> client.fetch(UnRegisteredExtension.class, "fake"));
assertThrows(SchemeNotFoundException.class, () ->
client.fetch(fromAPIVersionAndKind("fake.halo.run/v1alpha1", "UnRegistered"), "fake"));
when(converter.convertTo(any())).thenThrow(SchemeNotFoundException.class);
StepVerifier.create(client.create(createFakeExtension("fake", null)))
.verifyError(SchemeNotFoundException.class);
assertThrows(SchemeNotFoundException.class, () -> {
when(converter.convertTo(any())).thenThrow(SchemeNotFoundException.class);
client.update(createFakeExtension("fake", 1L));
});
assertThrows(SchemeNotFoundException.class, () -> {
when(converter.convertTo(any())).thenThrow(SchemeNotFoundException.class);
client.delete(createFakeExtension("fake", 1L));
});
}
@Test
void shouldReturnEmptyExtensions() {
when(storeClient.listByNamePrefix(anyString())).thenReturn(Flux.empty());
var fakes = client.list(FakeExtension.class, null, null);
StepVerifier.create(fakes)
.verifyComplete();
}
@Test
void shouldReturnExtensionsWithFilterAndSorter() {
var fake1 = createFakeExtension("fake-01", 1L);
var fake2 = createFakeExtension("fake-02", 1L);
when(
converter.convertFrom(FakeExtension.class, createExtensionStore("fake-01"))).thenReturn(
fake1);
when(
converter.convertFrom(FakeExtension.class, createExtensionStore("fake-02"))).thenReturn(
fake2);
when(storeClient.listByNamePrefix(anyString())).thenReturn(
Flux.fromIterable(
List.of(createExtensionStore("fake-01"), createExtensionStore("fake-02"))));
// without filter and sorter
Flux<FakeExtension> fakes =
client.list(FakeExtension.class, null, null);
StepVerifier.create(fakes)
.expectNext(fake1)
.expectNext(fake2)
.verifyComplete();
// with filter
fakes = client.list(FakeExtension.class, fake -> {
String name = fake.getMetadata().getName();
return "fake-01".equals(name);
}, null);
StepVerifier.create(fakes)
.expectNext(fake1)
.verifyComplete();
// with sorter
fakes = client.list(FakeExtension.class, null,
reverseOrder(comparing(fake -> fake.getMetadata().getName())));
StepVerifier.create(fakes)
.expectNext(fake2)
.expectNext(fake1)
.verifyComplete();
}
@Test
void shouldQueryPageableAndCorrectly() {
var fake1 = createFakeExtension("fake-01", 1L);
var fake2 = createFakeExtension("fake-02", 1L);
var fake3 = createFakeExtension("fake-03", 1L);
when(
converter.convertFrom(FakeExtension.class, createExtensionStore("fake-01"))).thenReturn(
fake1);
when(
converter.convertFrom(FakeExtension.class, createExtensionStore("fake-02"))).thenReturn(
fake2);
when(
converter.convertFrom(FakeExtension.class, createExtensionStore("fake-03"))).thenReturn(
fake3);
when(storeClient.listByNamePrefix(anyString())).thenReturn(Flux.fromIterable(
List.of(createExtensionStore("fake-01"), createExtensionStore("fake-02"),
createExtensionStore("fake-03"))));
// without filter and sorter.
var fakes = client.list(FakeExtension.class, null, null, 1, 10);
StepVerifier.create(fakes)
.expectNext(new ListResult<>(1, 10, 3, List.of(fake1, fake2, fake3)))
.verifyComplete();
// out of page range
fakes = client.list(FakeExtension.class, null, null, 100, 10);
StepVerifier.create(fakes)
.expectNext(new ListResult<>(100, 10, 3, emptyList()))
.verifyComplete();
// with filter only
fakes =
client.list(FakeExtension.class, fake -> "fake-03".equals(fake.getMetadata().getName()),
null, 1, 10);
StepVerifier.create(fakes)
.expectNext(new ListResult<>(1, 10, 1, List.of(fake3)))
.verifyComplete();
// with sorter only
fakes = client.list(FakeExtension.class, null,
reverseOrder(comparing(fake -> fake.getMetadata().getName())), 1, 10);
StepVerifier.create(fakes)
.expectNext(new ListResult<>(1, 10, 3, List.of(fake3, fake2, fake1)))
.verifyComplete();
// without page
fakes = client.list(FakeExtension.class, null, null, 0, 0);
StepVerifier.create(fakes)
.expectNext(new ListResult<>(0, 0, 3, List.of(fake1, fake2, fake3)))
.verifyComplete();
}
@Test
void shouldFetchNothing() {
when(storeClient.fetchByName(any())).thenReturn(Mono.empty());
var fake = client.fetch(FakeExtension.class, "fake");
StepVerifier.create(fake)
.verifyComplete();
verify(converter, times(0)).convertFrom(any(), any());
verify(storeClient, times(1)).fetchByName(any());
}
@Test
void shouldNotFetchUnstructured() {
when(schemeManager.get(isA(GroupVersionKind.class)))
.thenReturn(fakeScheme);
when(storeClient.fetchByName(any())).thenReturn(Mono.empty());
var unstructuredFake = client.fetch(fakeScheme.groupVersionKind(), "fake");
StepVerifier.create(unstructuredFake)
.verifyComplete();
verify(converter, times(0)).convertFrom(any(), any());
verify(schemeManager, times(1)).get(isA(GroupVersionKind.class));
verify(storeClient, times(1)).fetchByName(any());
}
@Test
void shouldFetchAnExtension() {
var storeName = "/registry/fake.halo.run/fakes/fake";
when(storeClient.fetchByName(storeName)).thenReturn(
Mono.just(createExtensionStore(storeName)));
when(
converter.convertFrom(FakeExtension.class, createExtensionStore(storeName))).thenReturn(
createFakeExtension("fake", 1L));
var fake = client.fetch(FakeExtension.class, "fake");
StepVerifier.create(fake)
.expectNext(createFakeExtension("fake", 1L))
.verifyComplete();
verify(storeClient, times(1)).fetchByName(eq(storeName));
verify(converter, times(1)).convertFrom(eq(FakeExtension.class),
eq(createExtensionStore(storeName)));
}
@Test
void shouldFetchUnstructuredExtension() throws JsonProcessingException {
var storeName = "/registry/fake.halo.run/fakes/fake";
when(storeClient.fetchByName(storeName)).thenReturn(
Mono.just(createExtensionStore(storeName)));
when(schemeManager.get(isA(GroupVersionKind.class)))
.thenReturn(fakeScheme);
when(converter.convertFrom(Unstructured.class, createExtensionStore(storeName)))
.thenReturn(createUnstructured());
var fake = client.fetch(fakeScheme.groupVersionKind(), "fake");
StepVerifier.create(fake)
.expectNext(createUnstructured())
.verifyComplete();
verify(storeClient, times(1)).fetchByName(eq(storeName));
verify(schemeManager, times(1)).get(isA(GroupVersionKind.class));
verify(converter, times(1)).convertFrom(eq(Unstructured.class),
eq(createExtensionStore(storeName)));
}
@Test
void shouldCreateSuccessfully() {
var fake = createFakeExtension("fake", null);
when(converter.convertTo(any())).thenReturn(
createExtensionStore("/registry/fake.halo.run/fakes/fake"));
when(storeClient.create(any(), any())).thenReturn(
Mono.just(createExtensionStore("/registry/fake.halo.run/fakes/fake")));
when(converter.convertFrom(same(FakeExtension.class), any())).thenReturn(fake);
var indexer = mock(Indexer.class);
when(indexerFactory.getIndexer(eq(fake.groupVersionKind()))).thenReturn(indexer);
StepVerifier.create(client.create(fake))
.expectNext(fake)
.verifyComplete();
verify(converter, times(1)).convertTo(eq(fake));
verify(storeClient, times(1)).create(eq("/registry/fake.halo.run/fakes/fake"), any());
assertNotNull(fake.getMetadata().getCreationTimestamp());
verify(indexer).indexRecord(eq(fake));
}
@Test
void shouldCreateWithGenerateNameSuccessfully() {
var fake = createFakeExtension("fake", null);
fake.getMetadata().setName("");
fake.getMetadata().setGenerateName("fake-");
when(converter.convertTo(any())).thenReturn(
createExtensionStore("/registry/fake.halo.run/fakes/fake"));
when(storeClient.create(any(), any())).thenReturn(
Mono.just(createExtensionStore("/registry/fake.halo.run/fakes/fake")));
when(converter.convertFrom(same(FakeExtension.class), any())).thenReturn(fake);
var indexer = mock(Indexer.class);
when(indexerFactory.getIndexer(eq(fake.groupVersionKind()))).thenReturn(indexer);
StepVerifier.create(client.create(fake))
.expectNext(fake)
.verifyComplete();
verify(converter, times(1)).convertTo(argThat(ext -> {
var name = ext.getMetadata().getName();
return name.startsWith(ext.getMetadata().getGenerateName());
}));
verify(storeClient, times(1)).create(eq("/registry/fake.halo.run/fakes/fake"), any());
assertNotNull(fake.getMetadata().getCreationTimestamp());
verify(indexer).indexRecord(eq(fake));
}
@Test
void shouldThrowExceptionIfCreatingWithoutGenerateName() {
var fake = createFakeExtension("fake", null);
fake.getMetadata().setName("");
fake.getMetadata().setGenerateName("");
StepVerifier.create(client.create(fake))
.verifyError(IllegalArgumentException.class);
}
@Test
void shouldThrowExceptionIfPrimaryKeyDuplicated() {
var fake = createFakeExtension("fake", null);
fake.getMetadata().setName("");
fake.getMetadata().setGenerateName("fake-");
when(converter.convertTo(any())).thenReturn(
createExtensionStore("/registry/fake.halo.run/fakes/fake"));
when(storeClient.create(any(), any())).thenThrow(DataIntegrityViolationException.class);
StepVerifier.create(client.create(fake))
.expectErrorMatches(Exceptions::isRetryExhausted)
.verify();
}
@Test
void shouldCreateUsingUnstructuredSuccessfully() throws JsonProcessingException {
var fake = createUnstructured();
when(converter.convertTo(any())).thenReturn(
createExtensionStore("/registry/fake.halo.run/fakes/fake"));
when(storeClient.create(any(), any())).thenReturn(
Mono.just(createExtensionStore("/registry/fake.halo.run/fakes/fake")));
when(converter.convertFrom(same(Unstructured.class), any())).thenReturn(fake);
var indexer = mock(Indexer.class);
when(indexerFactory.getIndexer(eq(fake.groupVersionKind()))).thenReturn(indexer);
StepVerifier.create(client.create(fake))
.expectNext(fake)
.verifyComplete();
verify(converter, times(1)).convertTo(eq(fake));
verify(storeClient, times(1)).create(eq("/registry/fake.halo.run/fakes/fake"), any());
assertNotNull(fake.getMetadata().getCreationTimestamp());
verify(indexer).indexRecord(assertArg(ext -> {
assertInstanceOf(FakeExtension.class, ext);
assertEquals("fake", ext.getMetadata().getName());
}));
}
@Test
void shouldUpdateSuccessfully() {
var fake = createFakeExtension("fake", 2L);
fake.getMetadata().setLabels(Map.of("new", "true"));
var storeName = "/registry/fake.halo.run/fakes/fake";
when(converter.convertTo(any())).thenReturn(
createExtensionStore(storeName, 2L));
when(storeClient.update(any(), any(), any())).thenReturn(
Mono.just(createExtensionStore(storeName, 2L)));
when(storeClient.fetchByName(storeName)).thenReturn(
Mono.just(createExtensionStore(storeName, 1L)));
var oldFake = createFakeExtension("fake", 2L);
oldFake.getMetadata().setLabels(Map.of("old", "true"));
var updatedFake = createFakeExtension("fake", 3L);
updatedFake.getMetadata().setLabels(Map.of("updated", "true"));
when(converter.convertFrom(same(FakeExtension.class), any()))
.thenReturn(oldFake)
.thenReturn(updatedFake);
var indexer = mock(Indexer.class);
when(indexerFactory.getIndexer(eq(fake.groupVersionKind()))).thenReturn(indexer);
StepVerifier.create(client.update(fake))
.expectNext(updatedFake)
.verifyComplete();
verify(storeClient).fetchByName(storeName);
verify(converter).convertTo(isA(JsonExtension.class));
verify(converter, times(2)).convertFrom(same(FakeExtension.class), any());
verify(storeClient)
.update(eq("/registry/fake.halo.run/fakes/fake"), eq(2L), any());
verify(indexer).updateRecord(eq(updatedFake));
}
@Test
void shouldNotUpdateIfExtensionNotChange() {
var fake = createFakeExtension("fake", 2L);
var storeName = "/registry/fake.halo.run/fakes/fake";
when(storeClient.fetchByName(storeName)).thenReturn(
Mono.just(createExtensionStore(storeName, 1L)));
var oldFake = createFakeExtension("fake", 2L);
when(converter.convertFrom(same(FakeExtension.class), any())).thenReturn(oldFake);
StepVerifier.create(client.update(fake))
.expectNext(fake)
.verifyComplete();
verify(storeClient).fetchByName(storeName);
verify(converter).convertFrom(same(FakeExtension.class), any());
verify(converter, never()).convertTo(any());
verify(storeClient, never()).update(any(), any(), any());
}
@Test
void shouldNotUpdateIfUnstructuredNotChange() throws JsonProcessingException {
var storeName = "/registry/fake.halo.run/fakes/fake";
var extensionStore = createExtensionStore(storeName, 2L);
when(storeClient.fetchByName(storeName)).thenReturn(
Mono.just(extensionStore));
var fakeJson = objectMapper.writeValueAsString(createFakeExtension("fake", 2L));
var oldFakeJson = objectMapper.writeValueAsString(createFakeExtension("fake", 2L));
var fake = objectMapper.readValue(fakeJson, Unstructured.class);
var oldFake = objectMapper.readValue(oldFakeJson, Unstructured.class);
oldFake.getMetadata().setVersion(2L);
when(converter.convertFrom(Unstructured.class, extensionStore)).thenReturn(oldFake);
StepVerifier.create(client.update(fake))
.expectNext(fake)
.verifyComplete();
verify(storeClient).fetchByName(storeName);
verify(converter).convertFrom(Unstructured.class, extensionStore);
verify(converter, never()).convertTo(any());
verify(storeClient, never()).update(any(), any(), any());
}
@Test
void shouldUpdateIfExtensionStatusChangedOnly() {
var fake = createFakeExtension("fake", 2L);
fake.getStatus().setState("new-state");
var storeName = "/registry/fake.halo.run/fakes/fake";
when(converter.convertTo(any())).thenReturn(
createExtensionStore(storeName, 2L));
when(storeClient.update(any(), any(), any())).thenReturn(
Mono.just(createExtensionStore(storeName, 2L)));
when(storeClient.fetchByName(storeName)).thenReturn(
Mono.just(createExtensionStore(storeName, 1L)));
var oldFake = createFakeExtension("fake", 2L);
oldFake.getStatus().setState("old-state");
var updatedFake = createFakeExtension("fake", 3L);
when(converter.convertFrom(same(FakeExtension.class), any()))
.thenReturn(oldFake)
.thenReturn(updatedFake);
var indexer = mock(Indexer.class);
when(indexerFactory.getIndexer(eq(fake.groupVersionKind()))).thenReturn(indexer);
StepVerifier.create(client.update(fake))
.expectNext(updatedFake)
.verifyComplete();
verify(storeClient).fetchByName(storeName);
verify(converter).convertTo(isA(JsonExtension.class));
verify(converter, times(2)).convertFrom(same(FakeExtension.class), any());
verify(storeClient)
.update(eq("/registry/fake.halo.run/fakes/fake"), eq(2L), any());
verify(indexer).updateRecord(eq(updatedFake));
}
@Test
void shouldUpdateUnstructuredSuccessfully() throws JsonProcessingException {
var fake = createUnstructured();
var name = "/registry/fake.halo.run/fakes/fake";
when(converter.convertTo(any()))
.thenReturn(createExtensionStore(name, 12345L));
when(storeClient.update(any(), any(), any()))
.thenReturn(Mono.just(createExtensionStore(name, 12345L)));
when(storeClient.fetchByName(name))
.thenReturn(Mono.just(createExtensionStore(name, 12346L)));
var oldFake = createUnstructured();
oldFake.getMetadata().setLabels(Map.of("old", "true"));
var updatedFake = createUnstructured();
updatedFake.getMetadata().setLabels(Map.of("updated", "true"));
when(converter.convertFrom(same(Unstructured.class), any()))
.thenReturn(oldFake)
.thenReturn(updatedFake);
var indexer = mock(Indexer.class);
when(indexerFactory.getIndexer(eq(fake.groupVersionKind()))).thenReturn(indexer);
StepVerifier.create(client.update(fake))
.expectNext(updatedFake)
.verifyComplete();
verify(storeClient).fetchByName(name);
verify(converter).convertTo(isA(JsonExtension.class));
verify(converter, times(2)).convertFrom(same(Unstructured.class), any());
verify(storeClient)
.update(eq("/registry/fake.halo.run/fakes/fake"), eq(12345L), any());
verify(indexer).updateRecord(assertArg(ext -> {
assertInstanceOf(FakeExtension.class, ext);
assertEquals("fake", ext.getMetadata().getName());
}));
}
@Test
void shouldDeleteSuccessfully() {
var fake = createFakeExtension("fake", 2L);
when(converter.convertTo(any())).thenReturn(
createExtensionStore("/registry/fake.halo.run/fakes/fake"));
when(storeClient.update(any(), any(), any())).thenReturn(
Mono.just(createExtensionStore("/registry/fake.halo.run/fakes/fake")));
when(converter.convertFrom(same(FakeExtension.class), any())).thenReturn(fake);
var indexer = mock(Indexer.class);
when(indexerFactory.getIndexer(eq(fake.groupVersionKind()))).thenReturn(indexer);
StepVerifier.create(client.delete(fake))
.expectNext(fake)
.verifyComplete();
verify(converter, times(1)).convertTo(any());
verify(storeClient, times(1)).update(any(), any(), any());
verify(storeClient, never()).delete(any(), any());
verify(indexer).updateRecord(eq(fake));
}
@Test
void shouldGetJsonExtension() {
var storeName = "/registry/fake.halo.run/fakes/fake";
when(storeClient.fetchByName(storeName)).thenReturn(
Mono.just(createExtensionStore(storeName)));
var fake = createFakeExtension("fake", 1L);
var expectedJsonExt = objectMapper.convertValue(fake, JsonExtension.class);
when(converter.convertFrom(JsonExtension.class, createExtensionStore(storeName)))
.thenReturn(expectedJsonExt);
var gvk = Scheme.buildFromType(FakeExtension.class).groupVersionKind();
StepVerifier.create(client.getJsonExtension(gvk, "fake"))
.expectNext(expectedJsonExt)
.verifyComplete();
verify(storeClient, times(1)).fetchByName(eq(storeName));
verify(converter, times(1)).convertFrom(eq(JsonExtension.class),
eq(createExtensionStore(storeName)));
}
@Nested
@DisplayName("Extension watcher test")
class WatcherTest {
@Mock
Watcher watcher;
@BeforeEach
void setUp() {
client.watch(watcher);
}
@Test
void shouldWatchOnAddSuccessfully() {
doNothing().when(watcher).onAdd(isA(Extension.class));
shouldCreateSuccessfully();
verify(watcher, times(1)).onAdd(isA(Extension.class));
}
@Test
void shouldWatchOnUpdateSuccessfully() {
doNothing().when(watcher).onUpdate(any(), any());
shouldUpdateSuccessfully();
verify(watcher, times(1)).onUpdate(any(), any());
}
@Test
void shouldNotWatchOnUpdateIfExtensionNotChange() {
shouldNotUpdateIfExtensionNotChange();
verify(watcher, never()).onUpdate(any(), any());
}
@Test
void shouldNotWatchOnUpdateIfExtensionStatusChangeOnly() {
shouldUpdateIfExtensionStatusChangedOnly();
verify(watcher, never()).onUpdate(any(), any());
}
@Test
void shouldWatchOnDeleteSuccessfully() {
doNothing().when(watcher).onDelete(any());
shouldDeleteSuccessfully();
verify(watcher, times(1)).onDelete(any());
}
@Test
void shouldWatchRealType() {
var extensionStore = createExtensionStore("/registry/fake.halo.run/fakes/fake");
var fake = createFakeExtension("fake", 1L);
var unstructured = Unstructured.OBJECT_MAPPER.convertValue(fake, Unstructured.class);
when(storeClient.fetchByName(extensionStore.getName()))
.thenReturn(Mono.just(extensionStore));
when(converter.convertTo(any())).thenReturn(extensionStore);
when(converter.convertFrom(same(Unstructured.class), any())).thenReturn(unstructured);
var indexer = mock(Indexer.class);
when(indexerFactory.getIndexer(eq(fake.groupVersionKind()))).thenReturn(indexer);
// on add
when(storeClient.create(any(), any())).thenReturn(Mono.just(extensionStore));
doNothing().when(watcher).onAdd(any(Extension.class));
StepVerifier.create(client.create(unstructured))
.expectNext(unstructured)
.verifyComplete();
verify(watcher, times(1)).onAdd(isA(FakeExtension.class));
// on update
when(storeClient.update(any(), any(), any())).thenReturn(Mono.just(extensionStore));
doNothing().when(watcher).onUpdate(any(), any());
StepVerifier.create(client.update(unstructured))
.expectNext(unstructured)
.verifyComplete();
verify(watcher, times(1))
.onUpdate(isA(FakeExtension.class), isA(FakeExtension.class));
// on delete
doNothing().when(watcher).onDelete(any());
StepVerifier.create(client.delete(unstructured))
.expectNext(unstructured)
.verifyComplete();
verify(watcher, times(1)).onDelete(isA(FakeExtension.class));
}
}
} | 29,191 | Java | .java | 605 | 38.879339 | 100 | 0.667686 | halo-dev/halo | 33,089 | 9,570 | 340 | GPL-3.0 | 9/4/2024, 7:04:55 PM (Europe/Amsterdam) | false | false | false | false | false | false | false |
21 | ReactiveExtensionStoreClientImplTest.java | halo-dev_halo/application/src/test/java/run/halo/app/extension/store/ReactiveExtensionStoreClientImplTest.java | package run.halo.app.extension.store;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@ExtendWith(MockitoExtension.class)
class ReactiveExtensionStoreClientImplTest {
@Mock
ExtensionStoreRepository repository;
@InjectMocks
ReactiveExtensionStoreClientImpl client;
@Test
void listByNamePrefix() {
var expectedExtensions = List.of(
new ExtensionStore("/registry/posts/hello-world", "this is post".getBytes(), 1L),
new ExtensionStore("/registry/posts/hello-halo", "this is post".getBytes(), 1L)
);
when(repository.findAllByNameStartingWith("/registry/posts"))
.thenReturn(Flux.fromIterable(expectedExtensions));
var gotExtensions = client.listByNamePrefix("/registry/posts").collectList().block();
assertEquals(expectedExtensions, gotExtensions);
}
@Test
void fetchByName() {
var expectedExtension =
new ExtensionStore("/registry/posts/hello-world", "this is post".getBytes(), 1L);
when(repository.findById("/registry/posts/hello-halo"))
.thenReturn(Mono.just(expectedExtension));
var gotExtension = client.fetchByName("/registry/posts/hello-halo").blockOptional();
assertTrue(gotExtension.isPresent());
assertEquals(expectedExtension, gotExtension.get());
}
@Test
void create() {
var expectedExtension =
new ExtensionStore("/registry/posts/hello-halo", "hello halo".getBytes(), 2L);
when(repository.save(any()))
.thenReturn(Mono.just(expectedExtension));
var createdExtension =
client.create("/registry/posts/hello-halo", "hello halo".getBytes())
.block();
assertEquals(expectedExtension, createdExtension);
}
@Test
void update() {
var expectedExtension =
new ExtensionStore("/registry/posts/hello-halo", "hello halo".getBytes(), 2L);
when(repository.save(any())).thenReturn(Mono.just(expectedExtension));
var updatedExtension =
client.update("/registry/posts/hello-halo", 1L, "hello halo".getBytes())
.block();
assertEquals(expectedExtension, updatedExtension);
}
@Test
void shouldDoNotThrowExceptionWhenDeletingNonExistExt() {
when(repository.findById(anyString())).thenReturn(Mono.empty());
client.delete("/registry/posts/hello-halo", 1L).block();
}
@Test
void shouldDeleteSuccessfully() {
var expectedExtension =
new ExtensionStore("/registry/posts/hello-halo", "hello halo".getBytes(), 2L);
when(repository.findById(anyString())).thenReturn(Mono.just(expectedExtension));
when(repository.delete(any())).thenReturn(Mono.empty());
var deletedExtension = client.delete("/registry/posts/hello-halo", 2L).block();
assertEquals(expectedExtension, deletedExtension);
}
} | 3,446 | Java | .java | 77 | 37.571429 | 93 | 0.704634 | halo-dev/halo | 33,089 | 9,570 | 340 | GPL-3.0 | 9/4/2024, 7:04:55 PM (Europe/Amsterdam) | false | false | false | false | false | false | false |
22 | ExtensionGetHandlerTest.java | halo-dev_halo/application/src/test/java/run/halo/app/extension/router/ExtensionGetHandlerTest.java | package run.halo.app.extension.router;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
import static run.halo.app.extension.GroupVersionKind.fromExtension;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.mock.web.reactive.function.server.MockServerRequest;
import org.springframework.web.reactive.function.server.EntityResponse;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import run.halo.app.extension.FakeExtension;
import run.halo.app.extension.ReactiveExtensionClient;
import run.halo.app.extension.Scheme;
import run.halo.app.extension.exception.ExtensionNotFoundException;
@ExtendWith(MockitoExtension.class)
class ExtensionGetHandlerTest {
@Mock
ReactiveExtensionClient client;
@Test
void shouldBuildPathPatternCorrectly() {
var scheme = Scheme.buildFromType(FakeExtension.class);
var getHandler = new ExtensionGetHandler(scheme, client);
var pathPattern = getHandler.pathPattern();
assertEquals("/apis/fake.halo.run/v1alpha1/fakes/{name}", pathPattern);
}
@Test
void shouldHandleCorrectly() {
var scheme = Scheme.buildFromType(FakeExtension.class);
var getHandler = new ExtensionGetHandler(scheme, client);
var serverRequest = MockServerRequest.builder()
.pathVariable("name", "my-fake")
.build();
final var fake = new FakeExtension();
when(client.get(eq(FakeExtension.class), eq("my-fake"))).thenReturn(Mono.just(fake));
var responseMono = getHandler.handle(serverRequest);
StepVerifier.create(responseMono)
.consumeNextWith(response -> {
assertEquals(HttpStatus.OK, response.statusCode());
assertEquals(MediaType.APPLICATION_JSON, response.headers().getContentType());
assertTrue(response instanceof EntityResponse<?>);
assertEquals(fake, ((EntityResponse<?>) response).entity());
})
.verifyComplete();
}
@Test
void shouldThrowExceptionWhenExtensionNotFound() {
var scheme = Scheme.buildFromType(FakeExtension.class);
var getHandler = new ExtensionGetHandler(scheme, client);
var serverRequest = MockServerRequest.builder()
.pathVariable("name", "my-fake")
.build();
when(client.get(eq(FakeExtension.class), eq("my-fake"))).thenReturn(Mono.error(
new ExtensionNotFoundException(fromExtension(FakeExtension.class), "my-fake")));
Mono<ServerResponse> responseMono = getHandler.handle(serverRequest);
StepVerifier.create(responseMono)
.expectError(ExtensionNotFoundException.class)
.verify();
}
}
| 3,163 | Java | .java | 66 | 41.257576 | 94 | 0.738257 | halo-dev/halo | 33,089 | 9,570 | 340 | GPL-3.0 | 9/4/2024, 7:04:55 PM (Europe/Amsterdam) | false | false | false | false | false | false | false |
23 | ExtensionRouterFunctionFactoryTest.java | halo-dev_halo/application/src/test/java/run/halo/app/extension/router/ExtensionRouterFunctionFactoryTest.java | package run.halo.app.extension.router;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.assertArg;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.github.fge.jackson.jsonpointer.JsonPointer;
import com.github.fge.jsonpatch.AddOperation;
import com.github.fge.jsonpatch.JsonPatch;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.codec.HttpMessageReader;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.web.server.MockServerWebExchange;
import org.springframework.test.web.reactive.server.WebTestClient;
import org.springframework.web.reactive.function.server.HandlerFunction;
import org.springframework.web.reactive.function.server.HandlerStrategies;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import run.halo.app.extension.FakeExtension;
import run.halo.app.extension.JsonExtension;
import run.halo.app.extension.Metadata;
import run.halo.app.extension.ReactiveExtensionClient;
import run.halo.app.extension.Scheme;
import run.halo.app.extension.router.ExtensionRouterFunctionFactory.CreateHandler;
import run.halo.app.extension.router.ExtensionRouterFunctionFactory.GetHandler;
import run.halo.app.extension.router.ExtensionRouterFunctionFactory.ListHandler;
import run.halo.app.extension.router.ExtensionRouterFunctionFactory.UpdateHandler;
@ExtendWith(MockitoExtension.class)
class ExtensionRouterFunctionFactoryTest {
@Mock
ReactiveExtensionClient client;
@Spy
Scheme scheme = Scheme.buildFromType(FakeExtension.class);
@InjectMocks
ExtensionRouterFunctionFactory factory;
WebTestClient webClient;
@BeforeEach
void setUp() {
webClient = WebTestClient.bindToRouterFunction(factory.create()).build();
}
@Nested
class PatchTest {
@Test
void shouldResponse404IfMethodNotPatch() {
webClient.method(HttpMethod.POST)
.uri("/apis/fake.halo.run/v1alpha1/fakes/my-fake")
.exchange()
.expectStatus().isNotFound();
}
@Test
void shouldResponse415IfMediaTypeIsInsufficient() {
webClient.method(HttpMethod.PATCH)
.uri("/apis/fake.halo.run/v1alpha1/fakes/my-fake")
.exchange()
.expectStatus().isEqualTo(HttpStatus.UNSUPPORTED_MEDIA_TYPE);
webClient.method(HttpMethod.PATCH)
.uri("/apis/fake.halo.run/v1alpha1/fakes/my-fake")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON.toString())
.exchange()
.expectStatus().isEqualTo(HttpStatus.UNSUPPORTED_MEDIA_TYPE);
}
@Test
void shouldResponseBadRequestIfNoPatchBody() {
webClient.method(HttpMethod.PATCH)
.uri("/apis/fake.halo.run/v1alpha1/fakes/my-fake")
.header(HttpHeaders.CONTENT_TYPE, "application/json-patch+json")
.exchange()
.expectStatus().isBadRequest();
}
@Test
void shouldPatchCorrectly() {
var fake = new FakeExtension();
var metadata = new Metadata();
metadata.setName("my-fake");
fake.setMetadata(metadata);
var mapper = Jackson2ObjectMapperBuilder.json().build();
var jsonExt = mapper.convertValue(fake, JsonExtension.class);
when(client.getJsonExtension(scheme.groupVersionKind(), "my-fake"))
.thenReturn(Mono.just(jsonExt));
var status = new FakeExtension.FakeStatus();
status.setState("running");
fake.setStatus(status);
var updatedExt = mapper.convertValue(fake, JsonExtension.class);
when(client.update(any(JsonExtension.class))).thenReturn(Mono.just(updatedExt));
var stateNode = JsonNodeFactory.instance.textNode("running");
var jsonPatch = new JsonPatch(List.of(
new AddOperation(JsonPointer.of("status", "state"), stateNode)
));
webClient.method(HttpMethod.PATCH)
.uri("/apis/fake.halo.run/v1alpha1/fakes/my-fake")
.header(HttpHeaders.CONTENT_TYPE, "application/json-patch+json")
.bodyValue(jsonPatch)
.exchange()
.expectStatus().isOk()
.expectBody(JsonExtension.class).isEqualTo(updatedExt);
verify(client).<JsonExtension>update(assertArg(ext -> {
var state = ext.getInternal().get("status").get("state")
.asText();
assertEquals("running", state);
}));
}
}
@Test
void shouldCreateSuccessfully() {
var routerFunction = factory.create();
testCases().forEach(testCase -> {
List<HttpMessageReader<?>> messageReaders =
HandlerStrategies.withDefaults().messageReaders();
var request = ServerRequest.create(testCase.webExchange, messageReaders);
var handlerFunc = routerFunction.route(request).block();
assertInstanceOf(testCase.expectHandlerType, handlerFunc);
});
}
List<TestCase> testCases() {
var listWebExchange = MockServerWebExchange.from(
MockServerHttpRequest.get("/apis/fake.halo.run/v1alpha1/fakes").build());
var getWebExchange = MockServerWebExchange.from(
MockServerHttpRequest.get("/apis/fake.halo.run/v1alpha1/fakes/my-fake").build()
);
var createWebExchange = MockServerWebExchange.from(
MockServerHttpRequest.post("/apis/fake.halo.run/v1alpha1/fakes").body("{}")
);
var updateWebExchange = MockServerWebExchange.from(
MockServerHttpRequest.put("/apis/fake.halo.run/v1alpha1/fakes/my-fake").body("{}")
);
return List.of(
new TestCase(listWebExchange, ListHandler.class),
new TestCase(getWebExchange, GetHandler.class),
new TestCase(createWebExchange, CreateHandler.class),
new TestCase(updateWebExchange, UpdateHandler.class)
);
}
record TestCase(ServerWebExchange webExchange,
Class<? extends HandlerFunction<ServerResponse>> expectHandlerType) {
}
} | 7,269 | Java | .java | 153 | 38.960784 | 94 | 0.704613 | halo-dev/halo | 33,089 | 9,570 | 340 | GPL-3.0 | 9/4/2024, 7:04:55 PM (Europe/Amsterdam) | false | false | false | false | false | false | false |
24 | ExtensionCompositeRouterFunctionTest.java | halo-dev_halo/application/src/test/java/run/halo/app/extension/router/ExtensionCompositeRouterFunctionTest.java | package run.halo.app.extension.router;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.web.server.MockServerWebExchange;
import org.springframework.web.reactive.function.server.HandlerStrategies;
import org.springframework.web.reactive.function.server.ServerRequest;
import run.halo.app.extension.FakeExtension;
import run.halo.app.extension.ReactiveExtensionClient;
import run.halo.app.extension.Scheme;
import run.halo.app.extension.SchemeManager;
import run.halo.app.extension.SchemeWatcherManager;
import run.halo.app.extension.SchemeWatcherManager.SchemeRegistered;
import run.halo.app.extension.SchemeWatcherManager.SchemeUnregistered;
@ExtendWith(MockitoExtension.class)
class ExtensionCompositeRouterFunctionTest {
@Mock
ReactiveExtensionClient client;
@Mock
SchemeManager schemeManager;
@Mock
SchemeWatcherManager watcherManager;
@InjectMocks
ExtensionCompositeRouterFunction extensionRouterFunc;
@Test
void shouldRouteWhenSchemeRegistered() {
var exchange = MockServerWebExchange.from(
MockServerHttpRequest.get("/apis/fake.halo.run/v1alpha1/fakes").build());
var messageReaders = HandlerStrategies.withDefaults().messageReaders();
ServerRequest request = ServerRequest.create(exchange, messageReaders);
var handlerFunc = extensionRouterFunc.route(request).block();
assertNull(handlerFunc);
// trigger registering scheme
extensionRouterFunc.onChange(
new SchemeRegistered(Scheme.buildFromType(FakeExtension.class)));
handlerFunc = extensionRouterFunc.route(request).block();
assertNotNull(handlerFunc);
}
@Test
void shouldNotRouteWhenSchemeUnregistered() {
var exchange = MockServerWebExchange.from(
MockServerHttpRequest.get("/apis/fake.halo.run/v1alpha1/fakes").build());
var messageReaders = HandlerStrategies.withDefaults().messageReaders();
// trigger registering scheme
extensionRouterFunc.onChange(
new SchemeRegistered(Scheme.buildFromType(FakeExtension.class)));
ServerRequest request = ServerRequest.create(exchange, messageReaders);
var handlerFunc = extensionRouterFunc.route(request).block();
assertNotNull(handlerFunc);
// trigger registering scheme
extensionRouterFunc.onChange(
new SchemeUnregistered(Scheme.buildFromType(FakeExtension.class)));
handlerFunc = extensionRouterFunc.route(request).block();
assertNull(handlerFunc);
}
@Test
void shouldRegisterWatcherAfterPropertiesSet() {
extensionRouterFunc.afterPropertiesSet();
verify(watcherManager).register(eq(extensionRouterFunc));
}
@Test
void shouldBuildRouterFunctionsOnApplicationStarted() {
var applicationStartedEvent = mock(ApplicationStartedEvent.class);
extensionRouterFunc.onApplicationEvent(applicationStartedEvent);
verify(schemeManager).schemes();
}
}
| 3,580 | Java | .java | 76 | 41.368421 | 85 | 0.783295 | halo-dev/halo | 33,089 | 9,570 | 340 | GPL-3.0 | 9/4/2024, 7:04:55 PM (Europe/Amsterdam) | false | false | false | false | false | false | false |
25 | ExtensionListHandlerTest.java | halo-dev_halo/application/src/test/java/run/halo/app/extension/router/ExtensionListHandlerTest.java | package run.halo.app.extension.router;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.same;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.web.reactive.function.server.MockServerRequest;
import org.springframework.mock.web.server.MockServerWebExchange;
import org.springframework.web.reactive.function.server.EntityResponse;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import run.halo.app.extension.FakeExtension;
import run.halo.app.extension.ListOptions;
import run.halo.app.extension.ListResult;
import run.halo.app.extension.ReactiveExtensionClient;
import run.halo.app.extension.Scheme;
@ExtendWith(MockitoExtension.class)
class ExtensionListHandlerTest {
@Mock
ReactiveExtensionClient client;
@Test
void shouldBuildPathPatternCorrectly() {
var scheme = Scheme.buildFromType(FakeExtension.class);
var listHandler = new ExtensionListHandler(scheme, client);
var pathPattern = listHandler.pathPattern();
assertEquals("/apis/fake.halo.run/v1alpha1/fakes", pathPattern);
}
@Test
void shouldHandleCorrectly() {
var scheme = Scheme.buildFromType(FakeExtension.class);
var listHandler = new ExtensionListHandler(scheme, client);
var exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/fake")
.queryParam("sort", "metadata.name,desc"));
var serverRequest = MockServerRequest.builder().exchange(exchange).build();
final var fake01 = FakeExtension.createFake("fake01");
final var fake02 = FakeExtension.createFake("fake02");
var fakeListResult = new ListResult<>(0, 0, 2, List.of(fake01, fake02));
when(client.listBy(same(FakeExtension.class), any(ListOptions.class), any()))
.thenReturn(Mono.just(fakeListResult));
var responseMono = listHandler.handle(serverRequest);
StepVerifier.create(responseMono)
.consumeNextWith(response -> {
assertEquals(HttpStatus.OK, response.statusCode());
assertEquals(MediaType.APPLICATION_JSON, response.headers().getContentType());
assertTrue(response instanceof EntityResponse<?>);
assertEquals(fakeListResult, ((EntityResponse<?>) response).entity());
})
.verifyComplete();
verify(client).listBy(same(FakeExtension.class), any(ListOptions.class), any());
}
}
| 2,994 | Java | .java | 60 | 44.15 | 94 | 0.757949 | halo-dev/halo | 33,089 | 9,570 | 340 | GPL-3.0 | 9/4/2024, 7:04:55 PM (Europe/Amsterdam) | false | false | false | false | false | false | false |
26 | ExtensionDeleteHandlerTest.java | halo-dev_halo/application/src/test/java/run/halo/app/extension/router/ExtensionDeleteHandlerTest.java | package run.halo.app.extension.router;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.same;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static run.halo.app.extension.GroupVersionKind.fromExtension;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.mock.web.reactive.function.server.MockServerRequest;
import org.springframework.web.reactive.function.server.EntityResponse;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import run.halo.app.extension.FakeExtension;
import run.halo.app.extension.Metadata;
import run.halo.app.extension.ReactiveExtensionClient;
import run.halo.app.extension.Scheme;
import run.halo.app.extension.Unstructured;
import run.halo.app.extension.exception.ExtensionNotFoundException;
@ExtendWith(MockitoExtension.class)
class ExtensionDeleteHandlerTest {
@Mock
ReactiveExtensionClient client;
@Test
void shouldBuildPathPatternCorrectly() {
var scheme = Scheme.buildFromType(FakeExtension.class);
var deleteHandler = new ExtensionDeleteHandler(scheme, client);
var pathPattern = deleteHandler.pathPattern();
assertEquals("/apis/fake.halo.run/v1alpha1/fakes/{name}", pathPattern);
}
@Test
void shouldHandleCorrectly() {
final var fake = new FakeExtension();
var metadata = new Metadata();
metadata.setName("my-fake");
fake.setMetadata(metadata);
var unstructured = new Unstructured();
unstructured.setMetadata(metadata);
unstructured.setApiVersion("fake.halo.run/v1alpha1");
unstructured.setKind("Fake");
var serverRequest = MockServerRequest.builder()
.pathVariable("name", "my-fake")
.body(Mono.just(unstructured));
when(client.get(eq(FakeExtension.class), eq("my-fake"))).thenReturn(Mono.just(fake));
when(client.delete(eq(fake))).thenReturn(Mono.just(fake));
var scheme = Scheme.buildFromType(FakeExtension.class);
var deleteHandler = new ExtensionDeleteHandler(scheme, client);
var responseMono = deleteHandler.handle(serverRequest);
StepVerifier.create(responseMono)
.assertNext(response -> {
assertEquals(HttpStatus.OK, response.statusCode());
assertEquals(MediaType.APPLICATION_JSON, response.headers().getContentType());
assertTrue(response instanceof EntityResponse<?>);
assertEquals(fake, ((EntityResponse<?>) response).entity());
})
.verifyComplete();
verify(client, times(1)).get(eq(FakeExtension.class), eq("my-fake"));
verify(client, times(1)).delete(any());
verify(client, times(0)).update(any());
}
@Test
void shouldReturnErrorWhenNoNameProvided() {
var serverRequest = MockServerRequest.builder()
.body(Mono.empty());
var scheme = Scheme.buildFromType(FakeExtension.class);
var deleteHandler = new ExtensionDeleteHandler(scheme, client);
assertThrows(IllegalArgumentException.class, () -> deleteHandler.handle(serverRequest));
}
@Test
void shouldReturnErrorWhenExtensionNotFound() {
var serverRequest = MockServerRequest.builder()
.pathVariable("name", "my-fake")
.build();
when(client.get(FakeExtension.class, "my-fake")).thenReturn(
Mono.error(
new ExtensionNotFoundException(fromExtension(FakeExtension.class), "my-fake")));
var scheme = Scheme.buildFromType(FakeExtension.class);
var deleteHandler = new ExtensionDeleteHandler(scheme, client);
var responseMono = deleteHandler.handle(serverRequest);
StepVerifier.create(responseMono)
.verifyError(ExtensionNotFoundException.class);
verify(client, times(1)).get(same(FakeExtension.class), anyString());
verify(client, times(0)).update(any());
verify(client, times(0)).delete(any());
}
}
| 4,594 | Java | .java | 95 | 41.557895 | 96 | 0.728814 | halo-dev/halo | 33,089 | 9,570 | 340 | GPL-3.0 | 9/4/2024, 7:04:55 PM (Europe/Amsterdam) | false | false | false | false | false | false | false |
27 | ExtensionCreateHandlerTest.java | halo-dev_halo/application/src/test/java/run/halo/app/extension/router/ExtensionCreateHandlerTest.java | package run.halo.app.extension.router;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.same;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.Objects;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.mock.web.reactive.function.server.MockServerRequest;
import org.springframework.web.reactive.function.server.EntityResponse;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import run.halo.app.extension.FakeExtension;
import run.halo.app.extension.Metadata;
import run.halo.app.extension.ReactiveExtensionClient;
import run.halo.app.extension.Scheme;
import run.halo.app.extension.Unstructured;
import run.halo.app.extension.exception.ExtensionConvertException;
import run.halo.app.extension.exception.ExtensionNotFoundException;
@ExtendWith(MockitoExtension.class)
class ExtensionCreateHandlerTest {
@Mock
ReactiveExtensionClient client;
@Test
void shouldBuildPathPatternCorrectly() {
var scheme = Scheme.buildFromType(FakeExtension.class);
var createHandler = new ExtensionCreateHandler(scheme, client);
var pathPattern = createHandler.pathPattern();
assertEquals("/apis/fake.halo.run/v1alpha1/fakes", pathPattern);
}
@Test
void shouldHandleCorrectly() {
final var fake = new FakeExtension();
var metadata = new Metadata();
metadata.setName("my-fake");
fake.setMetadata(metadata);
var unstructured = new Unstructured();
unstructured.setMetadata(metadata);
unstructured.setApiVersion("fake.halo.run/v1alpha1");
unstructured.setKind("Fake");
var serverRequest = MockServerRequest.builder()
.body(Mono.just(unstructured));
when(client.create(any(Unstructured.class))).thenReturn(Mono.just(unstructured));
var scheme = Scheme.buildFromType(FakeExtension.class);
var getHandler = new ExtensionCreateHandler(scheme, client);
var responseMono = getHandler.handle(serverRequest);
StepVerifier.create(responseMono)
.consumeNextWith(response -> {
assertEquals(HttpStatus.CREATED, response.statusCode());
assertEquals("/apis/fake.halo.run/v1alpha1/fakes/my-fake",
Objects.requireNonNull(response.headers().getLocation()).toString());
assertEquals(MediaType.APPLICATION_JSON, response.headers().getContentType());
assertTrue(response instanceof EntityResponse<?>);
assertEquals(unstructured, ((EntityResponse<?>) response).entity());
})
.verifyComplete();
verify(client, times(1)).create(eq(unstructured));
}
@Test
void shouldReturnErrorWhenNoBodyProvided() {
var serverRequest = MockServerRequest.builder()
.body(Mono.empty());
var scheme = Scheme.buildFromType(FakeExtension.class);
var getHandler = new ExtensionCreateHandler(scheme, client);
var responseMono = getHandler.handle(serverRequest);
StepVerifier.create(responseMono)
.verifyError(ExtensionConvertException.class);
}
@Test
void shouldReturnErrorWhenExtensionNotFound() {
final var unstructured = new Unstructured();
var metadata = new Metadata();
metadata.setName("my-fake");
unstructured.setMetadata(metadata);
unstructured.setApiVersion("fake.halo.run/v1alpha1");
unstructured.setKind("Fake");
var serverRequest = MockServerRequest.builder()
.body(Mono.just(unstructured));
doThrow(ExtensionNotFoundException.class).when(client).create(any());
var scheme = Scheme.buildFromType(FakeExtension.class);
var createHandler = new ExtensionCreateHandler(scheme, client);
var responseMono = createHandler.handle(serverRequest);
StepVerifier.create(responseMono)
.verifyError(ExtensionNotFoundException.class);
verify(client, times(1)).create(
argThat(extension -> Objects.equals("my-fake", extension.getMetadata().getName())));
verify(client, times(0)).fetch(same(FakeExtension.class), anyString());
}
}
| 4,835 | Java | .java | 100 | 41.52 | 96 | 0.737076 | halo-dev/halo | 33,089 | 9,570 | 340 | GPL-3.0 | 9/4/2024, 7:04:55 PM (Europe/Amsterdam) | false | false | false | false | false | false | false |
28 | PathPatternGeneratorTest.java | halo-dev_halo/application/src/test/java/run/halo/app/extension/router/PathPatternGeneratorTest.java | package run.halo.app.extension.router;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import run.halo.app.extension.AbstractExtension;
import run.halo.app.extension.GVK;
import run.halo.app.extension.Scheme;
import run.halo.app.extension.router.ExtensionRouterFunctionFactory.PathPatternGenerator;
class PathPatternGeneratorTest {
@GVK(group = "fake.halo.run", version = "v1alpha1", kind = "Fake",
singular = "fake", plural = "fakes")
private static class GroupExtension extends AbstractExtension {
}
@GVK(group = "", version = "v1alpha1", kind = "Fake",
singular = "fake", plural = "fakes")
private static class GrouplessExtension extends AbstractExtension {
}
@Test
void buildGroupedExtensionPathPattern() {
var scheme = Scheme.buildFromType(GroupExtension.class);
var pathPattern = PathPatternGenerator.buildExtensionPathPattern(scheme);
assertEquals("/apis/fake.halo.run/v1alpha1/fakes", pathPattern);
}
@Test
void buildGrouplessExtensionPathPattern() {
var scheme = Scheme.buildFromType(GrouplessExtension.class);
var pathPattern = PathPatternGenerator.buildExtensionPathPattern(scheme);
assertEquals("/api/v1alpha1/fakes", pathPattern);
}
} | 1,314 | Java | .java | 29 | 40.241379 | 89 | 0.749023 | halo-dev/halo | 33,089 | 9,570 | 340 | GPL-3.0 | 9/4/2024, 7:04:55 PM (Europe/Amsterdam) | false | false | false | false | false | false | false |
29 | ExtensionUpdateHandlerTest.java | halo-dev_halo/application/src/test/java/run/halo/app/extension/router/ExtensionUpdateHandlerTest.java | package run.halo.app.extension.router;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.same;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.Objects;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.mock.web.reactive.function.server.MockServerRequest;
import org.springframework.web.reactive.function.server.EntityResponse;
import org.springframework.web.server.ServerWebInputException;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import run.halo.app.extension.FakeExtension;
import run.halo.app.extension.Metadata;
import run.halo.app.extension.ReactiveExtensionClient;
import run.halo.app.extension.Scheme;
import run.halo.app.extension.Unstructured;
import run.halo.app.extension.exception.ExtensionNotFoundException;
@ExtendWith(MockitoExtension.class)
class ExtensionUpdateHandlerTest {
@Mock
ReactiveExtensionClient client;
@Test
void shouldBuildPathPatternCorrectly() {
var scheme = Scheme.buildFromType(FakeExtension.class);
var updateHandler = new ExtensionUpdateHandler(scheme, client);
var pathPattern = updateHandler.pathPattern();
assertEquals("/apis/fake.halo.run/v1alpha1/fakes/{name}", pathPattern);
}
@Test
void shouldHandleCorrectly() {
final var fake = new FakeExtension();
var metadata = new Metadata();
metadata.setName("my-fake");
fake.setMetadata(metadata);
var unstructured = new Unstructured();
unstructured.setMetadata(metadata);
unstructured.setApiVersion("fake.halo.run/v1alpha1");
unstructured.setKind("Fake");
var serverRequest = MockServerRequest.builder()
.pathVariable("name", "my-fake")
.body(Mono.just(unstructured));
// when(client.fetch(eq(FakeExtension.class), eq("my-fake"))).thenReturn(Mono.just(fake));
when(client.update(eq(unstructured))).thenReturn(Mono.just(unstructured));
var scheme = Scheme.buildFromType(FakeExtension.class);
var updateHandler = new ExtensionUpdateHandler(scheme, client);
var responseMono = updateHandler.handle(serverRequest);
StepVerifier.create(responseMono)
.assertNext(response -> {
assertEquals(HttpStatus.OK, response.statusCode());
assertEquals(MediaType.APPLICATION_JSON, response.headers().getContentType());
assertTrue(response instanceof EntityResponse<?>);
assertEquals(unstructured, ((EntityResponse<?>) response).entity());
})
.verifyComplete();
// verify(client, times(1)).fetch(eq(FakeExtension.class), eq("my-fake"));
verify(client, times(1)).update(eq(unstructured));
}
@Test
void shouldReturnErrorWhenNoBodyProvided() {
var serverRequest = MockServerRequest.builder()
.pathVariable("name", "my-fake")
.body(Mono.empty());
var scheme = Scheme.buildFromType(FakeExtension.class);
var updateHandler = new ExtensionUpdateHandler(scheme, client);
var responseMono = updateHandler.handle(serverRequest);
StepVerifier.create(responseMono)
.verifyError(ServerWebInputException.class);
}
@Test
void shouldReturnErrorWhenNoNameProvided() {
var serverRequest = MockServerRequest.builder()
.body(Mono.empty());
var scheme = Scheme.buildFromType(FakeExtension.class);
var updateHandler = new ExtensionUpdateHandler(scheme, client);
assertThrows(IllegalArgumentException.class, () -> updateHandler.handle(serverRequest));
}
@Test
void shouldReturnErrorWhenExtensionNotFound() {
final var unstructured = new Unstructured();
var metadata = new Metadata();
metadata.setName("my-fake");
unstructured.setMetadata(metadata);
unstructured.setApiVersion("fake.halo.run/v1alpha1");
unstructured.setKind("Fake");
var serverRequest = MockServerRequest.builder()
.pathVariable("name", "my-fake")
.body(Mono.just(unstructured));
doThrow(ExtensionNotFoundException.class).when(client).update(any());
var scheme = Scheme.buildFromType(FakeExtension.class);
var updateHandler = new ExtensionUpdateHandler(scheme, client);
var responseMono = updateHandler.handle(serverRequest);
StepVerifier.create(responseMono)
.verifyError(ExtensionNotFoundException.class);
verify(client, times(1)).update(
argThat(extension -> Objects.equals("my-fake", extension.getMetadata().getName())));
verify(client, times(0)).fetch(same(FakeExtension.class), anyString());
}
}
| 5,433 | Java | .java | 112 | 41.642857 | 98 | 0.730581 | halo-dev/halo | 33,089 | 9,570 | 340 | GPL-3.0 | 9/4/2024, 7:04:55 PM (Europe/Amsterdam) | false | false | false | false | false | false | false |
30 | IndexerFactoryImplTest.java | halo-dev_halo/application/src/test/java/run/halo/app/extension/index/IndexerFactoryImplTest.java | package run.halo.app.extension.index;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.List;
import java.util.Optional;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import run.halo.app.extension.AbstractExtension;
import run.halo.app.extension.GVK;
import run.halo.app.extension.GroupVersionKind;
import run.halo.app.extension.Scheme;
import run.halo.app.extension.SchemeManager;
/**
* Tests for {@link IndexerFactoryImpl}.
*
* @author guqing
* @since 2.12.0
*/
@ExtendWith(MockitoExtension.class)
class IndexerFactoryImplTest {
@Mock
private SchemeManager schemeManager;
@Mock
private IndexSpecRegistry indexSpecRegistry;
@InjectMocks
IndexerFactoryImpl indexerFactory;
@Test
@SuppressWarnings("unchecked")
void indexFactory() {
var scheme = Scheme.buildFromType(DemoExtension.class);
when(schemeManager.get(eq(DemoExtension.class)))
.thenReturn(scheme);
when(indexSpecRegistry.getKeySpace(scheme))
.thenReturn("/registry/test/demoextensions");
when(indexSpecRegistry.contains(eq(scheme)))
.thenReturn(false);
var specs = mock(IndexSpecs.class);
when(indexSpecRegistry.getIndexSpecs(eq(scheme)))
.thenReturn(specs);
when(specs.getIndexSpecs())
.thenReturn(List.of(PrimaryKeySpecUtils.primaryKeyIndexSpec(DemoExtension.class)));
ExtensionIterator<DemoExtension> iterator = mock(ExtensionIterator.class);
when(iterator.hasNext()).thenReturn(false);
// create indexer
var indexer = indexerFactory.createIndexerFor(DemoExtension.class, iterator);
assertThat(indexer).isNotNull();
when(schemeManager.fetch(eq(scheme.groupVersionKind()))).thenReturn(Optional.of(scheme));
when(schemeManager.get(eq(scheme.groupVersionKind()))).thenReturn(scheme);
// contains indexer
var hasIndexer = indexerFactory.contains(scheme.groupVersionKind());
assertThat(hasIndexer).isTrue();
assertThat(indexerFactory.contains(
new GroupVersionKind("test", "v1", "Post"))).isFalse();
// get indexer
var foundIndexer = indexerFactory.getIndexer(scheme.groupVersionKind());
assertThat(foundIndexer).isEqualTo(indexer);
// remove indexer
indexerFactory.removeIndexer(scheme);
assertThat(indexerFactory.contains(scheme.groupVersionKind())).isFalse();
// verify
verify(indexSpecRegistry).indexFor(eq(scheme));
verify(schemeManager).get(eq(DemoExtension.class));
verify(indexSpecRegistry, times(4)).getKeySpace(eq(scheme));
verify(indexSpecRegistry).contains(eq(scheme));
}
@Data
@EqualsAndHashCode(callSuper = true)
@GVK(group = "test", version = "v1", kind = "DemoExtension", plural = "demoextensions",
singular = "demoextension")
static class DemoExtension extends AbstractExtension {
private String email;
}
}
| 3,414 | Java | .java | 82 | 35.804878 | 97 | 0.733815 | halo-dev/halo | 33,089 | 9,570 | 340 | GPL-3.0 | 9/4/2024, 7:04:55 PM (Europe/Amsterdam) | false | false | false | false | false | false | false |
31 | PrimaryKeySpecUtilsTest.java | halo-dev_halo/application/src/test/java/run/halo/app/extension/index/PrimaryKeySpecUtilsTest.java | package run.halo.app.extension.index;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Set;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.junit.jupiter.api.Test;
import run.halo.app.extension.AbstractExtension;
import run.halo.app.extension.GVK;
import run.halo.app.extension.Metadata;
/**
* Tests for {@link PrimaryKeySpecUtils}.
*
* @author guqing
* @since 2.12.0
*/
class PrimaryKeySpecUtilsTest {
@Test
void primaryKeyIndexSpec() {
var spec =
PrimaryKeySpecUtils.primaryKeyIndexSpec(FakeExtension.class);
assertThat(spec.getName()).isEqualTo("metadata.name");
assertThat(spec.getOrder()).isEqualTo(IndexSpec.OrderType.ASC);
assertThat(spec.isUnique()).isTrue();
assertThat(spec.getIndexFunc()).isNotNull();
assertThat(spec.getIndexFunc().getObjectType()).isEqualTo(FakeExtension.class);
var extension = new FakeExtension();
extension.setMetadata(new Metadata());
extension.getMetadata().setName("fake-name-1");
assertThat(spec.getIndexFunc().getValues(extension))
.isEqualTo(Set.of("fake-name-1"));
}
@Data
@EqualsAndHashCode(callSuper = true)
@GVK(group = "test", version = "v1", kind = "FakeExtension", plural = "fakes",
singular = "fake")
static class FakeExtension extends AbstractExtension {
}
}
| 1,406 | Java | .java | 38 | 31.868421 | 87 | 0.713971 | halo-dev/halo | 33,089 | 9,570 | 340 | GPL-3.0 | 9/4/2024, 7:04:55 PM (Europe/Amsterdam) | false | false | false | false | false | false | false |
32 | LabelIndexSpecUtilsTest.java | halo-dev_halo/application/src/test/java/run/halo/app/extension/index/LabelIndexSpecUtilsTest.java | package run.halo.app.extension.index;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.util.Map;
import org.junit.jupiter.api.Test;
import run.halo.app.extension.AbstractExtension;
import run.halo.app.extension.Metadata;
/**
* Tests for {@link LabelIndexSpecUtils}.
*
* @author guqing
* @since 2.12.0
*/
class LabelIndexSpecUtilsTest {
@Test
void labelKeyValuePair() {
var pair = LabelIndexSpecUtils.labelKeyValuePair("key=value");
assertThat(pair.getFirst()).isEqualTo("key");
assertThat(pair.getSecond()).isEqualTo("value");
pair = LabelIndexSpecUtils.labelKeyValuePair("key=value=1");
assertThat(pair.getFirst()).isEqualTo("key");
assertThat(pair.getSecond()).isEqualTo("value=1");
assertThatThrownBy(() -> LabelIndexSpecUtils.labelKeyValuePair("key"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Invalid label key-value pair: key");
}
@Test
void labelIndexValueFunc() {
var ext = new TestExtension();
ext.setMetadata(new Metadata());
assertThat(LabelIndexSpecUtils.labelIndexValueFunc(ext)).isEmpty();
ext.getMetadata().setLabels(Map.of("key", "value", "key1", "value1"));
assertThat(LabelIndexSpecUtils.labelIndexValueFunc(ext)).containsExactlyInAnyOrder(
"key=value", "key1=value1");
}
static class TestExtension extends AbstractExtension {
}
}
| 1,532 | Java | .java | 38 | 34.605263 | 91 | 0.714286 | halo-dev/halo | 33,089 | 9,570 | 340 | GPL-3.0 | 9/4/2024, 7:04:55 PM (Europe/Amsterdam) | false | false | false | false | false | false | false |
33 | IndexedQueryEngineImplTest.java | halo-dev_halo/application/src/test/java/run/halo/app/extension/index/IndexedQueryEngineImplTest.java | package run.halo.app.extension.index;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static run.halo.app.extension.index.query.IndexViewDataSet.pileForIndexer;
import static run.halo.app.extension.index.query.QueryFactory.equal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.data.domain.Sort;
import run.halo.app.extension.AbstractExtension;
import run.halo.app.extension.GVK;
import run.halo.app.extension.GroupVersionKind;
import run.halo.app.extension.ListOptions;
import run.halo.app.extension.PageRequest;
import run.halo.app.extension.router.selector.EqualityMatcher;
import run.halo.app.extension.router.selector.FieldSelector;
import run.halo.app.extension.router.selector.LabelSelector;
import run.halo.app.extension.router.selector.SelectorMatcher;
/**
* Tests for {@link IndexedQueryEngineImpl}.
*
* @author guqing
* @since 2.12.0
*/
@ExtendWith(MockitoExtension.class)
class IndexedQueryEngineImplTest {
@Mock
private IndexerFactory indexerFactory;
@InjectMocks
private IndexedQueryEngineImpl indexedQueryEngine;
@Test
void retrieve() {
var spyIndexedQueryEngine = spy(indexedQueryEngine);
doReturn(List.of("object1", "object2", "object3")).when(spyIndexedQueryEngine)
.doRetrieve(any(), any(), eq(Sort.unsorted()));
var gvk = GroupVersionKind.fromExtension(DemoExtension.class);
var pageRequest = mock(PageRequest.class);
when(pageRequest.getPageNumber()).thenReturn(1);
when(pageRequest.getPageSize()).thenReturn(2);
when(pageRequest.getSort()).thenReturn(Sort.unsorted());
var result = spyIndexedQueryEngine.retrieve(gvk, new ListOptions(), pageRequest);
assertThat(result.getItems()).containsExactly("object1", "object2");
assertThat(result.getTotal()).isEqualTo(3);
verify(spyIndexedQueryEngine).doRetrieve(eq(gvk), any(), eq(Sort.unsorted()));
verify(pageRequest, times(2)).getPageNumber();
verify(pageRequest, times(2)).getPageSize();
verify(pageRequest).getSort();
}
@Test
void retrieveAll() {
var spyIndexedQueryEngine = spy(indexedQueryEngine);
doReturn(List.of()).when(spyIndexedQueryEngine)
.doRetrieve(any(), any(), eq(Sort.unsorted()));
var gvk = GroupVersionKind.fromExtension(DemoExtension.class);
var result = spyIndexedQueryEngine.retrieveAll(gvk, new ListOptions(), Sort.unsorted());
assertThat(result).isEmpty();
verify(spyIndexedQueryEngine).doRetrieve(eq(gvk), any(), eq(Sort.unsorted()));
}
@Test
void doRetrieve() {
var indexer = mock(Indexer.class);
var gvk = GroupVersionKind.fromExtension(DemoExtension.class);
when(indexerFactory.getIndexer(eq(gvk))).thenReturn(indexer);
pileForIndexer(indexer, PrimaryKeySpecUtils.PRIMARY_INDEX_NAME, List.of(
Map.entry("object1", "object1"),
Map.entry("object2", "object2"),
Map.entry("object3", "object3")
));
pileForIndexer(indexer, LabelIndexSpecUtils.LABEL_PATH, List.of(
Map.entry("key1=value1", "object1"),
Map.entry("key2=value2", "object1"),
Map.entry("key1=value1", "object2"),
Map.entry("key2=value2", "object2"),
Map.entry("key1=value1", "object3")
));
pileForIndexer(indexer, "slug", List.of(
Map.entry("slug1", "object1"),
Map.entry("slug2", "object2")
));
var listOptions = new ListOptions();
listOptions.setLabelSelector(LabelSelector.builder()
.eq("key1", "value1").build());
listOptions.setFieldSelector(FieldSelector.of(equal("slug", "slug1")));
var result = indexedQueryEngine.doRetrieve(gvk, listOptions, Sort.unsorted());
assertThat(result).containsExactly("object1");
}
@Data
@EqualsAndHashCode(callSuper = true)
@GVK(group = "test", version = "v1", kind = "demo", plural = "demos", singular = "demo")
static class DemoExtension extends AbstractExtension {
}
@Nested
@ExtendWith(MockitoExtension.class)
class LabelMatcherTest {
@InjectMocks
private IndexedQueryEngineImpl indexedQueryEngine;
@Test
void testRetrieveForLabelMatchers() {
// Setup mocks
IndexEntry indexEntryMock = mock(IndexEntry.class);
// Setup mock behavior
when(indexEntryMock.entries())
.thenReturn(List.of(Map.entry("key1=value1", "object1"),
Map.entry("key2=value2", "object1"),
Map.entry("key1=value1", "object2"),
Map.entry("key2=value2", "object2"),
Map.entry("key1=value1", "object3")));
var matcher1 = EqualityMatcher.equal("key1", "value1");
var matcher2 = EqualityMatcher.equal("key2", "value2");
List<SelectorMatcher> labelMatchers = Arrays.asList(matcher1, matcher2);
var indexer = mock(Indexer.class);
when(indexer.getIndexEntry(eq(LabelIndexSpecUtils.LABEL_PATH)))
.thenReturn(indexEntryMock);
var nameIndexEntry = mock(IndexEntry.class);
when(indexer.getIndexEntry(eq(PrimaryKeySpecUtils.PRIMARY_INDEX_NAME)))
.thenReturn(nameIndexEntry);
when(nameIndexEntry.entries()).thenReturn(List.of(Map.entry("object1", "object1"),
Map.entry("object2", "object2"), Map.entry("object3", "object3")));
// Test
assertThat(indexedQueryEngine.retrieveForLabelMatchers(indexer, labelMatchers))
.containsSequence("object1", "object2");
}
@Test
void testRetrieveForLabelMatchersNoMatch() {
IndexEntry indexEntryMock = mock(IndexEntry.class);
// Setup mock behavior
when(indexEntryMock.entries())
.thenReturn(List.of(Map.entry("key1=value1", "object1"),
Map.entry("key2=value2", "object2"),
Map.entry("key1=value3", "object3"))
);
var matcher1 = EqualityMatcher.equal("key3", "value3");
List<SelectorMatcher> labelMatchers = List.of(matcher1);
var indexer = mock(Indexer.class);
when(indexer.getIndexEntry(eq(LabelIndexSpecUtils.LABEL_PATH)))
.thenReturn(indexEntryMock);
var nameIndexEntry = mock(IndexEntry.class);
when(indexer.getIndexEntry(eq(PrimaryKeySpecUtils.PRIMARY_INDEX_NAME)))
.thenReturn(nameIndexEntry);
when(nameIndexEntry.entries()).thenReturn(List.of(Map.entry("object1", "object1"),
Map.entry("object2", "object2"), Map.entry("object3", "object3")));
// Test
assertThat(
indexedQueryEngine.retrieveForLabelMatchers(indexer, labelMatchers)).isEmpty();
}
}
}
| 7,657 | Java | .java | 162 | 38.703704 | 96 | 0.674394 | halo-dev/halo | 33,089 | 9,570 | 340 | GPL-3.0 | 9/4/2024, 7:04:55 PM (Europe/Amsterdam) | false | false | false | false | false | false | false |
34 | DefaultIndexSpecsTest.java | halo-dev_halo/application/src/test/java/run/halo/app/extension/index/DefaultIndexSpecsTest.java | package run.halo.app.extension.index;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static run.halo.app.extension.index.PrimaryKeySpecUtils.primaryKeyIndexSpec;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.junit.jupiter.api.Test;
import run.halo.app.extension.AbstractExtension;
import run.halo.app.extension.GVK;
/**
* Test for {@link DefaultIndexSpecs}.
*
* @author guqing
* @since 2.12.0
*/
class DefaultIndexSpecsTest {
@Test
void add() {
var specs = new DefaultIndexSpecs();
specs.add(primaryKeyIndexSpec(FakeExtension.class));
assertThat(specs.contains(PrimaryKeySpecUtils.PRIMARY_INDEX_NAME)).isTrue();
}
@Test
void addWithException() {
var specs = new DefaultIndexSpecs();
var nameSpec = new IndexSpec().setName("test");
assertThatThrownBy(() -> specs.add(nameSpec))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("IndexSpec indexFunc must not be null");
nameSpec.setIndexFunc(IndexAttributeFactory.simpleAttribute(FakeExtension.class,
e -> e.getMetadata().getName()));
specs.add(nameSpec);
assertThatThrownBy(() -> specs.add(nameSpec))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("IndexSpec with name test already exists");
}
@Test
void getIndexSpecs() {
var specs = new DefaultIndexSpecs();
specs.add(primaryKeyIndexSpec(FakeExtension.class));
assertThat(specs.getIndexSpecs()).hasSize(1);
}
@Test
void getIndexSpec() {
var specs = new DefaultIndexSpecs();
var nameSpec = primaryKeyIndexSpec(FakeExtension.class);
specs.add(nameSpec);
assertThat(specs.getIndexSpec(PrimaryKeySpecUtils.PRIMARY_INDEX_NAME)).isEqualTo(nameSpec);
}
@Test
void remove() {
var specs = new DefaultIndexSpecs();
var nameSpec = primaryKeyIndexSpec(FakeExtension.class);
specs.add(nameSpec);
assertThat(specs.contains(PrimaryKeySpecUtils.PRIMARY_INDEX_NAME)).isTrue();
specs.remove(PrimaryKeySpecUtils.PRIMARY_INDEX_NAME);
assertThat(specs.contains(PrimaryKeySpecUtils.PRIMARY_INDEX_NAME)).isFalse();
}
@Data
@EqualsAndHashCode(callSuper = true)
@GVK(group = "test", version = "v1", kind = "FakeExtension", plural = "fakeextensions",
singular = "fakeextension")
static class FakeExtension extends AbstractExtension {
private String email;
}
}
| 2,602 | Java | .java | 66 | 33.181818 | 99 | 0.707954 | halo-dev/halo | 33,089 | 9,570 | 340 | GPL-3.0 | 9/4/2024, 7:04:55 PM (Europe/Amsterdam) | false | false | false | false | false | false | false |
35 | IndexEntryOperatorImplTest.java | halo-dev_halo/application/src/test/java/run/halo/app/extension/index/IndexEntryOperatorImplTest.java | package run.halo.app.extension.index;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import run.halo.app.extension.index.query.IndexViewDataSet;
/**
* Tests for {@link IndexEntryOperatorImpl}.
*
* @author guqing
* @since 2.17.0
*/
@ExtendWith(MockitoExtension.class)
class IndexEntryOperatorImplTest {
@Mock
private IndexEntry indexEntry;
@InjectMocks
private IndexEntryOperatorImpl indexEntryOperator;
private LinkedHashMap<String, List<String>> createIndexedMapAndPile() {
var entries = new ArrayList<Map.Entry<String, String>>();
entries.add(Map.entry("apple", "A"));
entries.add(Map.entry("banana", "B"));
entries.add(Map.entry("cherry", "C"));
entries.add(Map.entry("date", "D"));
entries.add(Map.entry("egg", "E"));
entries.add(Map.entry("f", "F"));
var indexedMap = IndexViewDataSet.toKeyObjectMap(entries);
lenient().when(indexEntry.indexedKeys()).thenReturn(new TreeSet<>(indexedMap.keySet()));
lenient().when(indexEntry.getObjectNamesBy(anyString())).thenAnswer(invocation -> {
var key = (String) invocation.getArgument(0);
return indexedMap.get(key);
});
lenient().when(indexEntry.entries()).thenReturn(entries);
return indexedMap;
}
@Test
void lessThan() {
final var indexedMap = createIndexedMapAndPile();
var result = indexEntryOperator.lessThan("banana", false);
assertThat(result).containsExactly("A");
result = indexEntryOperator.lessThan("banana", true);
assertThat(result).containsExactly("A", "B");
result = indexEntryOperator.lessThan("cherry", true);
assertThat(result).containsExactly("A", "B", "C");
// does not exist key
result = indexEntryOperator.lessThan("z", false);
var objectIds = indexedMap.values().stream()
.flatMap(Collection::stream)
.toArray(String[]::new);
assertThat(result).contains(objectIds);
result = indexEntryOperator.lessThan("a", false);
assertThat(result).isEmpty();
}
@Test
void greaterThan() {
createIndexedMapAndPile();
var result = indexEntryOperator.greaterThan("banana", false);
assertThat(result).containsExactly("C", "D", "E", "F");
result = indexEntryOperator.greaterThan("banana", true);
assertThat(result).containsExactly("B", "C", "D", "E", "F");
result = indexEntryOperator.greaterThan("cherry", true);
assertThat(result).containsExactly("C", "D", "E", "F");
result = indexEntryOperator.greaterThan("cherry", false);
assertThat(result).containsExactly("D", "E", "F");
// does not exist key
result = indexEntryOperator.greaterThan("z", false);
assertThat(result).isEmpty();
}
@Test
void greaterThanForNumberString() {
var entries = List.of(
Map.entry("100", "1"),
Map.entry("101", "2"),
Map.entry("102", "3"),
Map.entry("103", "4"),
Map.entry("110", "5"),
Map.entry("111", "6"),
Map.entry("112", "7"),
Map.entry("120", "8")
);
var indexedMap = IndexViewDataSet.toKeyObjectMap(entries);
when(indexEntry.indexedKeys()).thenReturn(new TreeSet<>(indexedMap.keySet()));
lenient().when(indexEntry.getObjectNamesBy(anyString())).thenAnswer(invocation -> {
var key = (String) invocation.getArgument(0);
return indexedMap.get(key);
});
when(indexEntry.entries()).thenReturn(entries);
var result = indexEntryOperator.greaterThan("102", false);
assertThat(result).containsExactly("4", "5", "6", "7", "8");
result = indexEntryOperator.greaterThan("110", false);
assertThat(result).containsExactly("6", "7", "8");
}
@Test
void range() {
createIndexedMapAndPile();
var result = indexEntryOperator.range("banana", "date", true, false);
assertThat(result).containsExactly("B", "C");
result = indexEntryOperator.range("banana", "date", false, false);
assertThat(result).containsExactly("C");
result = indexEntryOperator.range("banana", "date", true, true);
assertThat(result).containsExactly("B", "C", "D");
result = indexEntryOperator.range("apple", "egg", false, true);
assertThat(result).containsExactly("B", "C", "D", "E");
// end not exist
result = indexEntryOperator.range("d", "z", false, false);
assertThat(result).containsExactly("D", "E", "F");
// start key > end key
assertThatThrownBy(() -> indexEntryOperator.range("z", "f", false, false))
.isInstanceOf(IllegalArgumentException.class);
// both not exist
result = indexEntryOperator.range("z", "zz", false, false);
assertThat(result).isEmpty();
}
@Test
void findTest() {
createIndexedMapAndPile();
var result = indexEntryOperator.find("banana");
assertThat(result).containsExactly("B");
result = indexEntryOperator.find("date");
assertThat(result).containsExactly("D");
result = indexEntryOperator.find("z");
assertThat(result).isEmpty();
}
@Test
void findInTest() {
createIndexedMapAndPile();
var result = indexEntryOperator.findIn(List.of("banana", "date"));
assertThat(result).containsExactly("B", "D");
}
} | 6,108 | Java | .java | 142 | 35.514085 | 96 | 0.649359 | halo-dev/halo | 33,089 | 9,570 | 340 | GPL-3.0 | 9/4/2024, 7:04:55 PM (Europe/Amsterdam) | false | false | false | false | false | false | false |
36 | IndexDescriptorTest.java | halo-dev_halo/application/src/test/java/run/halo/app/extension/index/IndexDescriptorTest.java | package run.halo.app.extension.index;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import run.halo.app.extension.FakeExtension;
/**
* Tests for {@link IndexDescriptor}.
*
* @author guqing
* @since 2.12.0
*/
class IndexDescriptorTest {
@Test
void equalsVerifier() {
var spec1 = new IndexSpec()
.setName("metadata.name")
.setOrder(IndexSpec.OrderType.ASC)
.setIndexFunc(IndexAttributeFactory.simpleAttribute(FakeExtension.class,
e -> e.getMetadata().getName())
)
.setUnique(true);
var descriptor = new IndexDescriptor(spec1);
var descriptor2 = new IndexDescriptor(spec1);
assertThat(descriptor).isEqualTo(descriptor2);
var spec2 = new IndexSpec()
.setName("metadata.name")
.setOrder(IndexSpec.OrderType.DESC)
.setIndexFunc(IndexAttributeFactory.simpleAttribute(FakeExtension.class,
e -> e.getMetadata().getName())
)
.setUnique(false);
var descriptor3 = new IndexDescriptor(spec2);
assertThat(descriptor).isEqualTo(descriptor3);
}
}
| 1,209 | Java | .java | 34 | 27.764706 | 84 | 0.655261 | halo-dev/halo | 33,089 | 9,570 | 340 | GPL-3.0 | 9/4/2024, 7:04:55 PM (Europe/Amsterdam) | false | false | false | false | false | false | false |
37 | DefaultExtensionIteratorTest.java | halo-dev_halo/application/src/test/java/run/halo/app/extension/index/DefaultExtensionIteratorTest.java | package run.halo.app.extension.index;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.List;
import java.util.NoSuchElementException;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import run.halo.app.extension.Extension;
/**
* Tests for {@link DefaultExtensionIterator}.
*
* @author guqing
* @since 2.12.0
*/
@ExtendWith(MockitoExtension.class)
class DefaultExtensionIteratorTest {
@Mock
private ExtensionPaginatedLister<Extension> lister;
@Test
@SuppressWarnings("unchecked")
void testConstructor_loadsData() {
Page<Extension> page = mock(Page.class);
when(page.getContent()).thenReturn(List.of(mock(Extension.class)));
when(page.hasNext()).thenReturn(true);
when(page.nextPageable()).thenReturn(
PageRequest.of(1, DefaultExtensionIterator.DEFAULT_PAGE_SIZE, Sort.by("name")));
when(lister.list(any())).thenReturn(page);
var iterator = new DefaultExtensionIterator<>(lister);
assertThat(iterator.hasNext()).isTrue();
}
@Test
@SuppressWarnings("unchecked")
void hasNext_whenNextPageExists_loadsNextPage() {
Page<Extension> page1 = mock(Page.class);
when(page1.getContent()).thenReturn(List.of(mock(Extension.class)));
when(page1.hasNext()).thenReturn(true);
when(page1.nextPageable()).thenReturn(
PageRequest.of(1, DefaultExtensionIterator.DEFAULT_PAGE_SIZE, Sort.by("name")));
Page<Extension> page2 = mock(Page.class);
when(page2.getContent()).thenReturn(List.of(mock(Extension.class)));
when(page2.hasNext()).thenReturn(false);
when(lister.list(any(Pageable.class))).thenReturn(page1, page2);
var iterator = new DefaultExtensionIterator<>(lister);
// consume first page
iterator.next();
// should load the next page
assertThat(iterator.hasNext()).isTrue();
}
@Test
@SuppressWarnings("unchecked")
void next_whenNoNextElement_throwsException() {
Page<Extension> page = mock(Page.class);
when(page.getContent()).thenReturn(List.of(mock(Extension.class)));
when(page.hasNext()).thenReturn(false);
when(lister.list(any())).thenReturn(page);
var iterator = new DefaultExtensionIterator<>(lister);
// consume only element
iterator.next();
assertThatThrownBy(iterator::next).isInstanceOf(NoSuchElementException.class);
}
}
| 2,968 | Java | .java | 70 | 36.771429 | 92 | 0.725286 | halo-dev/halo | 33,089 | 9,570 | 340 | GPL-3.0 | 9/4/2024, 7:04:55 PM (Europe/Amsterdam) | false | false | false | false | false | false | false |
38 | DefaultIndexerTest.java | halo-dev_halo/application/src/test/java/run/halo/app/extension/index/DefaultIndexerTest.java | package run.halo.app.extension.index;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.util.List;
import java.util.Map;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import run.halo.app.extension.AbstractExtension;
import run.halo.app.extension.GVK;
import run.halo.app.extension.Metadata;
import run.halo.app.infra.exception.DuplicateNameException;
/**
* Tests for {@link DefaultIndexer}.
*
* @author guqing
* @since 2.12.0
*/
@ExtendWith(MockitoExtension.class)
class DefaultIndexerTest {
private static FakeExtension createFakeExtension() {
var fake = new FakeExtension();
fake.setMetadata(new Metadata());
fake.getMetadata().setName("fake-extension");
fake.setEmail("fake-email");
return fake;
}
private static IndexSpec getNameIndexSpec() {
return getIndexSpec("metadata.name", true,
IndexAttributeFactory.simpleAttribute(FakeExtension.class,
e -> e.getMetadata().getName()));
}
private static IndexSpec getIndexSpec(String name, boolean unique, IndexAttribute attribute) {
return new IndexSpec()
.setName(name)
.setOrder(IndexSpec.OrderType.ASC)
.setUnique(unique)
.setIndexFunc(attribute);
}
@Test
void constructor() {
var spec = getNameIndexSpec();
var descriptor = new IndexDescriptor(spec);
descriptor.setReady(true);
var indexContainer = new IndexEntryContainer();
indexContainer.add(new IndexEntryImpl(descriptor));
new DefaultIndexer(List.of(descriptor), indexContainer);
}
@Test
void constructorWithException() {
var spec = getNameIndexSpec();
var descriptor = new IndexDescriptor(spec);
var indexContainer = new IndexEntryContainer();
assertThatThrownBy(() -> new DefaultIndexer(List.of(descriptor), indexContainer))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Index descriptor is not ready for: metadata.name");
descriptor.setReady(true);
assertThatThrownBy(() -> new DefaultIndexer(List.of(descriptor), indexContainer))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Index entry not found for: metadata.name");
}
@Test
void getIndexEntryTest() {
var spec = getNameIndexSpec();
var descriptor = new IndexDescriptor(spec);
descriptor.setReady(true);
var indexContainer = new IndexEntryContainer();
indexContainer.add(new IndexEntryImpl(descriptor));
var defaultIndexer = new DefaultIndexer(List.of(descriptor), indexContainer);
assertThatThrownBy(() -> defaultIndexer.getIndexEntry("not-exist"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("No index found for fieldPath [not-exist], "
+ "make sure you have created an index for this field.");
assertThat(defaultIndexer.getIndexEntry("metadata.name")).isNotNull();
}
@Test
void getObjectKey() {
var fake = createFakeExtension();
assertThat(DefaultIndexer.getObjectKey(fake)).isEqualTo("fake-extension");
}
@Test
void indexRecord() {
var nameIndex = getNameIndexSpec();
var indexContainer = new IndexEntryContainer();
var descriptor = new IndexDescriptor(nameIndex);
descriptor.setReady(true);
indexContainer.add(new IndexEntryImpl(descriptor));
var indexer = new DefaultIndexer(List.of(descriptor), indexContainer);
indexer.indexRecord(createFakeExtension());
var iterator = indexer.allIndexesIterator();
assertThat(iterator.hasNext()).isTrue();
var indexEntry = iterator.next();
var entries = indexEntry.entries();
assertThat(entries).hasSize(1);
assertThat(entries).contains(Map.entry("fake-extension", "fake-extension"));
}
@Test
void indexRecordWithExceptionShouldRollback() {
var indexContainer = new IndexEntryContainer();
// add email before name
var emailDescriptor = new IndexDescriptor(getIndexSpec("email", false,
IndexAttributeFactory.simpleAttribute(FakeExtension.class, FakeExtension::getEmail)));
emailDescriptor.setReady(true);
var emailIndexEntry = new IndexEntryImpl(emailDescriptor);
indexContainer.add(emailIndexEntry);
var descriptor = new IndexDescriptor(getNameIndexSpec());
descriptor.setReady(true);
var nameIndexEntry = new IndexEntryImpl(descriptor);
indexContainer.add(nameIndexEntry);
var indexer = new DefaultIndexer(List.of(descriptor, emailDescriptor), indexContainer);
indexer.indexRecord(createFakeExtension());
assertThat(emailIndexEntry.entries()).hasSize(1);
assertThat(nameIndexEntry.entries()).hasSize(1);
var fake2 = createFakeExtension();
fake2.setEmail("email-2");
// email applied to entry then name duplicate
assertThatThrownBy(() -> indexer.indexRecord(fake2))
.isInstanceOf(DuplicateNameException.class)
.hasMessage(
"400 BAD_REQUEST \"The value [fake-extension] is already exists for unique index "
+ "[metadata.name].\"");
// should be rollback email-2 key
assertThat(emailIndexEntry.entries()).hasSize(1);
assertThat(nameIndexEntry.entries()).hasSize(1);
}
@Test
void updateRecordWithExceptionShouldRollback() {
var indexContainer = new IndexEntryContainer();
// add email before name
var emailDescriptor = new IndexDescriptor(getIndexSpec("email", false,
IndexAttributeFactory.simpleAttribute(FakeExtension.class, FakeExtension::getEmail)));
emailDescriptor.setReady(true);
var emailIndexEntry = new IndexEntryImpl(emailDescriptor);
indexContainer.add(emailIndexEntry);
var descriptor = new IndexDescriptor(getNameIndexSpec());
descriptor.setReady(true);
var nameIndexEntry = new IndexEntryImpl(descriptor);
indexContainer.add(nameIndexEntry);
var indexer = new DefaultIndexer(List.of(descriptor, emailDescriptor), indexContainer);
var fakeExtension = createFakeExtension();
indexer.indexRecord(fakeExtension);
assertThat(emailIndexEntry.entries()).hasSize(1);
assertThat(emailIndexEntry.entries()).contains(Map.entry("fake-email", "fake-extension"));
assertThat(nameIndexEntry.entries()).hasSize(1);
assertThat(nameIndexEntry.entries()).contains(
Map.entry("fake-extension", "fake-extension"));
fakeExtension.setEmail("email-2");
indexer.updateRecord(fakeExtension);
assertThat(emailIndexEntry.entries()).hasSize(1);
assertThat(emailIndexEntry.entries()).contains(Map.entry("email-2", "fake-extension"));
assertThat(nameIndexEntry.entries()).hasSize(1);
assertThat(nameIndexEntry.entries()).contains(
Map.entry("fake-extension", "fake-extension"));
fakeExtension.getMetadata().setName("fake-extension-2");
indexer.updateRecord(fakeExtension);
assertThat(emailIndexEntry.entries())
.containsExactly(Map.entry("email-2", "fake-extension"),
Map.entry("email-2", "fake-extension-2"));
assertThat(nameIndexEntry.entries())
.containsExactly(Map.entry("fake-extension", "fake-extension"),
Map.entry("fake-extension-2", "fake-extension-2"));
}
@Test
void findIndexByName() {
var indexContainer = new IndexEntryContainer();
// add email before name
var emailDescriptor = new IndexDescriptor(getIndexSpec("email", false,
IndexAttributeFactory.simpleAttribute(FakeExtension.class, FakeExtension::getEmail)));
emailDescriptor.setReady(true);
var emailIndexEntry = new IndexEntryImpl(emailDescriptor);
indexContainer.add(emailIndexEntry);
var descriptor = new IndexDescriptor(getNameIndexSpec());
descriptor.setReady(true);
var nameIndexEntry = new IndexEntryImpl(descriptor);
indexContainer.add(nameIndexEntry);
var indexer = new DefaultIndexer(List.of(descriptor, emailDescriptor), indexContainer);
var foundNameDescriptor = indexer.findIndexByName("metadata.name");
assertThat(foundNameDescriptor).isNotNull();
assertThat(foundNameDescriptor).isEqualTo(descriptor);
var foundEmailDescriptor = indexer.findIndexByName("email");
assertThat(foundEmailDescriptor).isNotNull();
assertThat(foundEmailDescriptor).isEqualTo(emailDescriptor);
}
@Test
void createIndexEntry() {
var nameSpec = getNameIndexSpec();
var descriptor = new IndexDescriptor(nameSpec);
descriptor.setReady(true);
var indexContainer = new IndexEntryContainer();
indexContainer.add(new IndexEntryImpl(descriptor));
var indexer = new DefaultIndexer(List.of(descriptor), indexContainer);
var indexEntry = indexer.createIndexEntry(descriptor);
assertThat(indexEntry).isNotNull();
}
@Test
void removeIndexRecord() {
var nameIndex = getNameIndexSpec();
var indexContainer = new IndexEntryContainer();
var descriptor = new IndexDescriptor(nameIndex);
descriptor.setReady(true);
var nameIndexEntry = new IndexEntryImpl(descriptor);
indexContainer.add(nameIndexEntry);
var indexer = new DefaultIndexer(List.of(descriptor), indexContainer);
indexer.indexRecord(createFakeExtension());
assertThat(nameIndexEntry.entries())
.containsExactly(Map.entry("fake-extension", "fake-extension"));
indexer.removeIndexRecords(d -> true);
assertThat(nameIndexEntry.entries()).isEmpty();
}
@Test
void readyIndexesIterator() {
var indexContainer = new IndexEntryContainer();
var descriptor = new IndexDescriptor(getNameIndexSpec());
descriptor.setReady(true);
var nameIndexEntry = new IndexEntryImpl(descriptor);
indexContainer.add(nameIndexEntry);
var indexer = new DefaultIndexer(List.of(descriptor), indexContainer);
var iterator = indexer.readyIndexesIterator();
assertThat(iterator.hasNext()).isTrue();
descriptor.setReady(false);
iterator = indexer.readyIndexesIterator();
assertThat(iterator.hasNext()).isFalse();
}
@Data
@EqualsAndHashCode(callSuper = true)
@GVK(group = "test", version = "v1", kind = "FakeExtension", plural = "fakeextensions",
singular = "fakeextension")
static class FakeExtension extends AbstractExtension {
private String email;
}
}
| 11,068 | Java | .java | 233 | 39.253219 | 98 | 0.696414 | halo-dev/halo | 33,089 | 9,570 | 340 | GPL-3.0 | 9/4/2024, 7:04:55 PM (Europe/Amsterdam) | false | false | false | false | false | false | false |
39 | IndexSpecRegistryImplTest.java | halo-dev_halo/application/src/test/java/run/halo/app/extension/index/IndexSpecRegistryImplTest.java | package run.halo.app.extension.index;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.util.Set;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.junit.jupiter.MockitoExtension;
import run.halo.app.extension.AbstractExtension;
import run.halo.app.extension.GVK;
import run.halo.app.extension.Scheme;
/**
* Tests for {@link IndexSpecRegistryImpl}.
*
* @author guqing
* @since 2.12.0
*/
@ExtendWith(MockitoExtension.class)
class IndexSpecRegistryImplTest {
@InjectMocks
private IndexSpecRegistryImpl indexSpecRegistry;
private final Scheme scheme = Scheme.buildFromType(FakeExtension.class);
@AfterEach
void tearDown() {
indexSpecRegistry.removeIndexSpecs(scheme);
}
@Test
void indexFor() {
var specs = indexSpecRegistry.indexFor(scheme);
assertThat(specs).isNotNull();
assertThat(specs.getIndexSpecs()).hasSize(4);
}
@Test
void contains() {
indexSpecRegistry.indexFor(scheme);
assertThat(indexSpecRegistry.contains(scheme)).isTrue();
}
@Test
void getKeySpace() {
var keySpace = indexSpecRegistry.getKeySpace(scheme);
assertThat(keySpace).isEqualTo("/registry/test.halo.run/fakes");
}
@Test
void getIndexSpecs() {
assertThatThrownBy(() -> indexSpecRegistry.getIndexSpecs(scheme))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("No index specs found for extension type: ");
indexSpecRegistry.indexFor(scheme);
var specs = indexSpecRegistry.getIndexSpecs(scheme);
assertThat(specs).isNotNull();
}
@Data
@EqualsAndHashCode(callSuper = true)
@GVK(group = "test.halo.run", version = "v1", kind = "FakeExtension", plural = "fakes",
singular = "fake")
static class FakeExtension extends AbstractExtension {
Set<String> tags;
}
}
| 2,153 | Java | .java | 62 | 29.790323 | 91 | 0.731731 | halo-dev/halo | 33,089 | 9,570 | 340 | GPL-3.0 | 9/4/2024, 7:04:55 PM (Europe/Amsterdam) | false | false | false | false | false | false | false |
End of preview. Expand
in Dataset Viewer.
README.md exists but content is empty.
- Downloads last month
- 3