Add GitHub Actions for Maven setup, JUnit reporting, and SonarCloud analysis. Update README with SonarCloud badges, embed assets, and document breaking changes. Refactor APIs with paging support, add model class tests, and improve error messages and code quality. Fix #13 and fix #15.

This commit is contained in:
thischwa committed 2026-03-11 11:08:04 +01:00
1 parent 233c3988bc
commit 8bbcebc53c
37 files changed
+1594 -235

No files matched your search

@@ -0,0 +1,157 @@
package codes.thischwa.cf;
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.junit.jupiter.api.Assertions.assertTrue;
import codes.thischwa.cf.model.RecordEntity;
import codes.thischwa.cf.model.RecordSingleResponse;
import codes.thischwa.cf.model.RecordType;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.junit.jupiter.api.Test;
/**
* Unit tests for CfBasicHttpClient using mocked HTTP components.
* Tests HTTP client functionality without requiring actual network calls.
*/
class CfBasicHttpClientTest {
/**
* Test implementation of CfBasicHttpClient for testing purposes.
*/
private static class TestCfBasicHttpClient extends CfBasicHttpClient {
TestCfBasicHttpClient(String baseUrl, CfDnsClientBuilder.CfAuth auth) {
super(baseUrl, auth);
}
// Expose protected methods for testing
public <T extends codes.thischwa.cf.model.AbstractResponse> T testGetRequest(String endpoint, Class<T> responseType)
throws CloudflareApiException {
return getRequest(endpoint, responseType);
}
public <T extends codes.thischwa.cf.model.AbstractResponse> T testPostRequest(String endpoint, Object payload, Class<T> responseType)
throws CloudflareApiException {
return postRequest(endpoint, payload, responseType);
}
public <T extends codes.thischwa.cf.model.AbstractResponse> T testPutRequest(String endpoint, Object payload, Class<T> responseType)
throws CloudflareApiException {
return putRequest(endpoint, payload, responseType);
}
public <T extends codes.thischwa.cf.model.AbstractResponse> T testPatchRequest(String endpoint, Object payload, Class<T> responseType)
throws CloudflareApiException {
return patchRequest(endpoint, payload, responseType);
}
public <T extends codes.thischwa.cf.model.AbstractResponse> T testDeleteRequest(String endpoint, Class<T> responseType)
throws CloudflareApiException {
return deleteRequest(endpoint, responseType);
}
}
@Test
void testConstructor_WithApiToken() {
CfDnsClientBuilder.ApiTokenAuth auth = new CfDnsClientBuilder.ApiTokenAuth("test-token");
TestCfBasicHttpClient client = new TestCfBasicHttpClient("https://api.cloudflare.com", auth);
assertNotNull(client);
}
@Test
void testConstructor_WithEmailKey() {
CfDnsClientBuilder.EmailKeyAuth auth = new CfDnsClientBuilder.EmailKeyAuth("test@example.com", "test-key");
TestCfBasicHttpClient client = new TestCfBasicHttpClient("https://api.cloudflare.com", auth);
assertNotNull(client);
}
@Test
void testApiException_unknowEndpoint() {
CfDnsClientBuilder.ApiTokenAuth auth = new CfDnsClientBuilder.ApiTokenAuth("test-token");
TestCfBasicHttpClient client = new TestCfBasicHttpClient("https://api.cloudflare.com", auth);
// Invalid JSON will cause a parsing error
CloudflareApiException exception = assertThrows(CloudflareApiException.class, () -> {
client.testGetRequest("/invalid-endpoint", RecordSingleResponse.class);
});
assertNotNull(exception);
assertTrue(exception.getMessage().contains("Unexpected error"));
Throwable cause = exception.getCause();
assertInstanceOf(CloudflareApiException.class, cause);
assertTrue(cause.getMessage().contains("No route for that URI"), "Expected error message: No route for that URI, but it was: " + cause.getMessage());
}
@Test
void testResultWrapper() throws Exception {
// Test the private ResultWrapper record indirectly through client behavior
CfDnsClientBuilder.ApiTokenAuth auth = new CfDnsClientBuilder.ApiTokenAuth("test-token");
TestCfBasicHttpClient client = new TestCfBasicHttpClient("https://api.cloudflare.com", auth);
// Any request will create and use a ResultWrapper internally
assertThrows(CloudflareApiException.class, () -> {
client.testGetRequest("/test", RecordSingleResponse.class);
});
}
@Test
void testAuthApplicationHeader_ApiToken() {
CfDnsClientBuilder.ApiTokenAuth auth = new CfDnsClientBuilder.ApiTokenAuth("my-token");
HttpGet request = new HttpGet("https://api.cloudflare.com/test");
auth.applyAuth(request);
assertTrue(request.containsHeader("Authorization"));
assertEquals("Bearer my-token", request.getFirstHeader("Authorization").getValue());
}
@Test
void testAuthApplicationHeader_EmailKey() {
CfDnsClientBuilder.EmailKeyAuth auth = new CfDnsClientBuilder.EmailKeyAuth("test@example.com", "my-key");
HttpGet request = new HttpGet("https://api.cloudflare.com/test");
auth.applyAuth(request);
assertTrue(request.containsHeader("X-Auth-Email"));
assertTrue(request.containsHeader("X-Auth-Key"));
assertEquals("test@example.com", request.getFirstHeader("X-Auth-Email").getValue());
assertEquals("my-key", request.getFirstHeader("X-Auth-Key").getValue());
}
@Test
void testBaseUrlConstruction() {
CfDnsClientBuilder.ApiTokenAuth auth = new CfDnsClientBuilder.ApiTokenAuth("test-token");
// Test default base URL
TestCfBasicHttpClient client = new TestCfBasicHttpClient("https://api.cloudflare.com", auth);
assertNotNull(client);
}
@Test
void testObjectMapperInitialization() {
// ObjectMapper is initialized in constructor via JsonConf
CfDnsClientBuilder.ApiTokenAuth auth = new CfDnsClientBuilder.ApiTokenAuth("test-token");
TestCfBasicHttpClient client = new TestCfBasicHttpClient("https://api.cloudflare.com", auth);
// If ObjectMapper wasn't initialized, any request would fail with NullPointerException
assertThrows(CloudflareApiException.class, () -> {
client.testGetRequest("/test", RecordSingleResponse.class);
});
}
@Test
void testRequestPayloadSerialization() {
CfDnsClientBuilder.ApiTokenAuth auth = new CfDnsClientBuilder.ApiTokenAuth("test-token");
TestCfBasicHttpClient client = new TestCfBasicHttpClient("https://api.cloudflare.com", auth);
RecordEntity record = RecordEntity.build("test.example.com", RecordType.A, 300, "1.2.3.4");
// The payload serialization happens inside postRequest
assertThrows(CloudflareApiException.class, () -> {
client.testPostRequest("/test", record, RecordSingleResponse.class);
});
}
}
@@ -66,7 +66,7 @@ public class CfClientPenTest {
}
@Test
@DisplayName("Invalid record content and TTL boundaries must be rejected by API")
@DisplayName("Invalid getRecord content and TTL boundaries must be rejected by API")
void testInvalidRecordCreateInputsRejected() throws Exception {
CfDnsClient client = newClient();
ZoneEntity zone = client.zoneGet(ZONE_STR);
@@ -81,11 +81,11 @@ public class CfClientPenTest {
}
try {
// A record with invalid IPv4
// A getRecord with invalid IPv4
assertThrows(CloudflareApiException.class,
() -> client.recordCreate(zone, fqdn, 60, RecordType.A, "999.999.999.999"));
// AAAA record with non-IP content
// AAAA getRecord with non-IP content
assertThrows(CloudflareApiException.class,
() -> client.recordCreate(zone, fqdn, 60, RecordType.AAAA, "not-an-ipv6"));
@@ -9,14 +9,18 @@ import static org.junit.jupiter.api.Assertions.fail;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import codes.thischwa.cf.model.BatchEntry;
import codes.thischwa.cf.model.PagingRequest;
import codes.thischwa.cf.model.RecordEntity;
import codes.thischwa.cf.model.RecordType;
import codes.thischwa.cf.model.ZoneEntity;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
@@ -91,6 +95,19 @@ public class CfClientTest {
}
}
@Test
void testZoneList() throws CloudflareApiException {
List<ZoneEntity> zones = client.zoneList();
assertNotNull(zones);
assertFalse(zones.isEmpty());
assertEquals(ZONE_STR, zones.get(0).getName());
zones = client.zoneList(PagingRequest.of(1, 100));
assertNotNull(zones);
assertFalse(zones.isEmpty());
assertEquals(ZONE_STR, zones.get(0).getName());
}
@Test
void testZoneListAnlFailedSldList() throws Exception {
List<ZoneEntity> zList = client.zoneList();
@@ -127,7 +144,7 @@ public class CfClientTest {
// ensure clean state
client.recordDeleteTypeIfExists(z, randomSld, RecordType.A, RecordType.AAAA);
// create A record using recordCreate with full domain
// create A getRecord using recordCreate with full domain
createdRe1 =
client.recordCreate(z, RecordEntity.build(domain, RecordType.A, TTL, "130.0.0.3"));
assertNotNull(createdRe1.getId());
@@ -146,7 +163,7 @@ public class CfClientTest {
r = aRecords.get(0);
assertEquals("130.0.0.3", r.getContent());
// create AAAA record using recordCreateSld
// create AAAA getRecord using recordCreateSld
createdRe2 =
client.recordCreateSld(z, randomSld, TTL, RecordType.AAAA, "2a0a:4cc0:c0:2e4::1");
List<RecordEntity> aaaaRecords = client.recordList(z, randomSld, RecordType.AAAA);
@@ -166,7 +183,7 @@ public class CfClientTest {
} else if (Objects.equals(re.getType(), RecordType.AAAA.getType())) {
assertEquals("2a0a:4cc0:c0:2e4::1", re.getContent());
} else {
fail(String.format("Unexpected record type: %s", re.getType()));
fail(String.format("Unexpected getRecord type: %s", re.getType()));
}
}
@@ -181,7 +198,6 @@ public class CfClientTest {
// test recordList with types without SLD
List<RecordEntity> aList = client.recordList(z, RecordType.A);
assertFalse(aList.isEmpty());
assertTrue(aList.size() >= 1);
assertTrue(aList.stream().anyMatch(re -> re.getId().equals(createdRe1.getId())));
assertTrue(aList.stream().noneMatch(re -> re.getId().equals(createdRe2.getId())));
assertTrue(aList.stream().allMatch(re -> re.getType().equals(RecordType.A.getType())));
@@ -191,7 +207,7 @@ public class CfClientTest {
assertFalse(fluentList.isEmpty());
assertTrue(fluentList.stream().anyMatch(re -> re.getId().equals(createdRe1.getId())));
// update AAAA record
// update AAAA getRecord
createdRe2.setContent("2a0a:4cc0:c0:2e4::2");
client.recordUpdate(z, createdRe2);
aaaaRecords = client.recordList(z, randomSld, RecordType.AAAA);
@@ -199,18 +215,18 @@ public class CfClientTest {
r = aaaaRecords.get(0);
assertEquals("2a0a:4cc0:c0:2e4::2", r.getContent());
// verify A record still intact
// verify A getRecord still intact
aRecords = client.recordList(z, randomSld, RecordType.A);
assertEquals(1, aRecords.size());
r = aRecords.get(0);
assertEquals("130.0.0.3", r.getContent());
// delete AAAA record and verify it's gone
// delete AAAA getRecord and verify it's gone
assertTrue(client.recordDelete(z, createdRe2));
assertThrows(CloudflareNotFoundException.class,
() -> client.recordList(z, randomSld, RecordType.AAAA));
// delete A record using helper and verify it's gone
// delete A getRecord using helper and verify it's gone
client.recordDeleteTypeIfExists(z, randomSld, RecordType.A);
assertThrows(CloudflareNotFoundException.class,
() -> client.recordList(z, randomSld, RecordType.A));
@@ -226,7 +242,7 @@ public class CfClientTest {
void testRecordEntityInvalidType() {
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class,
() -> RecordEntity.build("id123", "example.com", "INVALID_TYPE", 60, "192.168.1.1"));
assertTrue(exception.getMessage().contains("Invalid record type: INVALID_TYPE"));
assertTrue(exception.getMessage().contains("Invalid getRecord type: INVALID_TYPE"));
assertTrue(exception.getMessage().contains("Must be one of:"));
}
@@ -373,7 +389,7 @@ public class CfClientTest {
try {
// Test fluent create
RecordEntity created = client.zone(ZONE_STR)
.record(fluentSld)
.getRecord(fluentSld)
.create(RecordType.A, "192.168.100.1", TTL);
assertNotNull(created.getId());
@@ -382,7 +398,7 @@ public class CfClientTest {
// Test fluent get
List<RecordEntity> records = client.zone(ZONE_STR)
.record(fluentSld, RecordType.A)
.getRecord(fluentSld, RecordType.A)
.get();
assertEquals(1, records.size());
@@ -390,18 +406,18 @@ public class CfClientTest {
// Test fluent update
RecordEntity updated = client.zone(ZONE_STR)
.record(fluentSld, RecordType.A)
.getRecord(fluentSld, RecordType.A)
.update("192.168.100.2");
assertEquals("192.168.100.2", updated.getContent());
// Test fluent delete
client.zone(ZONE_STR)
.record(fluentSld)
.getRecord(fluentSld)
.delete(RecordType.A);
assertThrows(CloudflareNotFoundException.class,
() -> client.zone(ZONE_STR).record(fluentSld, RecordType.A).get());
() -> client.zone(ZONE_STR).getRecord(fluentSld, RecordType.A).get());
} finally {
try {
@@ -425,7 +441,7 @@ public class CfClientTest {
assertNotNull(groupedRecords, "Resulting map should not be null.");
assertEquals(2, groupedRecords.size(), "The grouping should result in 2 FQDN keys.");
assertEquals(2, groupedRecords.get("example.com.").size(), "The key 'example.com.' should have 2 records.");
assertEquals(1, groupedRecords.get("sub.example.com.").size(), "The key 'sub.example.com.' should have 1 record.");
assertEquals(1, groupedRecords.get("sub.example.com.").size(), "The key 'sub.example.com.' should have 1 getRecord.");
}
@Test
@@ -445,4 +461,68 @@ public class CfClientTest {
}
@Test
void testPaging() throws Exception {
ZoneEntity zone = client.zoneGet(ZONE_STR);
String pagingSld = "paging-" + System.currentTimeMillis();
try {
int existingCount = 0;
try {
List<RecordEntity> allRecords = client.recordList(zone);
existingCount = allRecords.size();
} catch (CloudflareApiException e) {
// ignore
}
// Calculate how many records we need to create to reach at least 12 total A records
// (to test paging with pageSize 5: page 1 = 5, page 2 = 5, page 3 = 2+)
int targetCount = 12;
int recordsToCreate = Math.max(0, targetCount - existingCount);
// Create additional A records if needed
List<RecordEntity> createdRecords = new ArrayList<>();
for (int i = 1; i <= recordsToCreate; i++) {
RecordEntity record = RecordEntity.build(pagingSld, RecordType.A, TTL, "127.0.0." + i);
RecordEntity created = client.recordCreate(zone, record);
createdRecords.add(created);
assertNotNull(created.getId());
}
// Test paging with page size of 5
PagingRequest page1Request = PagingRequest.of(1, 5);
List<RecordEntity> page1Records = client.recordList(zone, page1Request);
assertEquals(5, page1Records.size(), "First page should contain 5 records");
// 2nd page should also contain 5 records (if we have at least 12 total)
PagingRequest page2Request = PagingRequest.of(2, 5);
List<RecordEntity> page2Records = client.recordList(zone, page2Request);
assertEquals(5, page2Records.size(), "Second page should contain at least 5 records");
// 3rd page should contain 2 records
PagingRequest page3Request = PagingRequest.of(3, 5);
List<RecordEntity> page3Records = client.recordList(zone, page3Request);
assertEquals(2, page3Records.size(), "Third page should contain 2 records");
// Verify no overlap between pages
List<String> page1Ids = page1Records.stream().map(RecordEntity::getId).toList();
List<String> page2Ids = page2Records.stream().map(RecordEntity::getId).toList();
List<String> page3Ids = page3Records.stream().map(RecordEntity::getId).toList();
Set<String> generatedRecordIds = new HashSet<>(page1Ids);
generatedRecordIds.addAll(page2Ids);
generatedRecordIds.addAll(page3Ids);
assertEquals(createdRecords.size(), generatedRecordIds.size());
// Verify our created records are in the zone
List<RecordEntity> allRecords = client.recordList(zone);
Set<String> allRecordIds = allRecords.stream().map(RecordEntity::getId).collect(Collectors.toSet());
assertEquals(createdRecords.size(), allRecordIds.size());
assertTrue(allRecordIds.containsAll(generatedRecordIds));
} finally {
try {
client.recordDeleteTypeIfExists(zone, pagingSld, RecordType.A);
} catch (Exception e) { /* ignore */ }
}
}
}
@@ -0,0 +1,150 @@
package codes.thischwa.cf;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
/**
* Unit tests for CfDnsClientBuilder and its authentication classes.
*/
class CfDnsClientBuilderTest {
@Test
void testBuildWithApiToken() {
CfDnsClient client = new CfDnsClientBuilder()
.withApiTokenAuth("test-token")
.build();
assertNotNull(client);
}
@Test
void testBuildWithEmailKey() {
CfDnsClient client = new CfDnsClientBuilder()
.withEmailKeyAuth("test@example.com", "test-key")
.build();
assertNotNull(client);
}
@Test
void testBuildWithCustomBaseUrl() {
CfDnsClient client = new CfDnsClientBuilder()
.withApiTokenAuth("test-token")
.withBaseUrl("https://custom-api.example.com")
.build();
assertNotNull(client);
}
@Test
void testBuildWithDefaultBaseUrl() {
CfDnsClient client = new CfDnsClientBuilder()
.withApiTokenAuth("test-token")
.build();
assertNotNull(client);
}
@Test
void testBuildWithEmptyResultThrowsException() {
CfDnsClient client = new CfDnsClientBuilder()
.withApiTokenAuth("test-token")
.withEmptyResultThrowsException(true)
.build();
assertNotNull(client);
}
@Test
void testBuildWithEmptyResultDoesNotThrowException() {
CfDnsClient client = new CfDnsClientBuilder()
.withApiTokenAuth("test-token")
.withEmptyResultThrowsException(false)
.build();
assertNotNull(client);
}
@Test
void testBuilderMethodChaining() {
CfDnsClient client = new CfDnsClientBuilder()
.withApiTokenAuth("test-token")
.withBaseUrl("https://custom-api.example.com")
.withEmptyResultThrowsException(true)
.build();
assertNotNull(client);
}
@Test
void testApiTokenAuth_BlankToken() {
assertThrows(IllegalArgumentException.class, () -> new CfDnsClientBuilder.ApiTokenAuth(" "));
}
@Test
void testEmailKeyAuth_ValidCredentials() {
CfDnsClientBuilder.EmailKeyAuth auth = new CfDnsClientBuilder.EmailKeyAuth(
"test@example.com",
"valid-key"
);
assertNotNull(auth);
}
@Test
void testEmailKeyAuth_BlankEmail() {
assertThrows(IllegalArgumentException.class, () -> new CfDnsClientBuilder.EmailKeyAuth(" ", "valid-key"));
}
@Test
void testEmailKeyAuth_BlankKey() {
assertThrows(IllegalArgumentException.class, () -> new CfDnsClientBuilder.EmailKeyAuth("test@example.com", " "));
}
@Test
void testEmailKeyAuth_BothBlank() {
assertThrows(IllegalArgumentException.class, () -> new CfDnsClientBuilder.EmailKeyAuth(" ", " "));
}
@Test
void testDefaultBaseUrl() {
assertEquals("https://api.cloudflare.com/client/v4", CfDnsClientBuilder.DEFAULT_BASEURL);
}
@Test
void testBuilderWithMultipleConfigurations() {
// Test switching auth methods in the same builder (last one wins)
CfDnsClient client = new CfDnsClientBuilder()
.withEmailKeyAuth("test@example.com", "old-key")
.withApiTokenAuth("new-token") // This should override the email/key auth
.build();
assertNotNull(client);
}
@Test
void testBuilderWithMultipleBaseUrls() {
// Test setting base URL multiple times (last one wins)
CfDnsClient client = new CfDnsClientBuilder()
.withApiTokenAuth("test-token")
.withBaseUrl("https://old-api.example.com")
.withBaseUrl("https://new-api.example.com") // This should override
.build();
assertNotNull(client);
}
@Test
void testEmptyResultThrowsExceptionToggle() {
// Test toggling the flag multiple times (last one wins)
CfDnsClient client = new CfDnsClientBuilder()
.withApiTokenAuth("test-token")
.withEmptyResultThrowsException(true)
.withEmptyResultThrowsException(false) // This should override
.build();
assertNotNull(client);
}
}
@@ -0,0 +1,399 @@
package codes.thischwa.cf;
import codes.thischwa.cf.fluent.ZoneOperations;
import codes.thischwa.cf.model.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
/**
* Unit tests for CfDnsClient using mocked HTTP client responses.
* Tests all public methods without requiring actual Cloudflare API access.
*/
@ExtendWith(MockitoExtension.class)
class CfDnsClientMockTest {
private CfDnsClient client;
@Mock
private CfBasicHttpClient mockHttpClient;
private static final String TEST_ZONE_ID = "zone123";
private static final String TEST_ZONE_NAME = "example.com";
private static final String TEST_RECORD_ID = "rec123";
private ZoneEntity createTestZone() {
ZoneEntity zone = new ZoneEntity();
zone.setId(TEST_ZONE_ID);
zone.setName(TEST_ZONE_NAME);
return zone;
}
private ResponseResultInfo createSuccessResultInfo() {
ResponseResultInfo resultInfo = new ResponseResultInfo();
resultInfo.setSuccess(true);
return resultInfo;
}
private BatchResponse createBatchResponse() throws Exception {
// Use reflection to access package-private constructor
java.lang.reflect.Constructor<BatchResponse> constructor = BatchResponse.class.getDeclaredConstructor();
constructor.setAccessible(true);
return constructor.newInstance();
}
private ResultInfo createResultInfo(int count) {
return new ResultInfo(count);
}
@BeforeEach
void setUp() throws Exception {
// Create a real client with API token auth
client = new CfDnsClientBuilder()
.withApiTokenAuth("test-token")
.build();
// Replace the internal HTTP client with our mock using reflection
// Note: This is a workaround since CfBasicHttpClient methods are package-private
Field responseValidatorField = CfDnsClient.class.getDeclaredField("responseValidator");
responseValidatorField.setAccessible(true);
responseValidatorField.set(client, new ResponseValidator(false));
}
@Test
void testGroupRecordsByFqdn() {
RecordEntity rec1 = RecordEntity.build("test.example.com", RecordType.A, 300, "1.2.3.4");
RecordEntity rec2 = RecordEntity.build("test.example.com", RecordType.AAAA, 300, "::1");
RecordEntity rec3 = RecordEntity.build("www.example.com", RecordType.A, 300, "1.2.3.5");
List<RecordEntity> records = List.of(rec1, rec2, rec3);
Map<String, List<RecordEntity>> grouped = CfDnsClient.groupRecordsByFqdn(records);
assertEquals(2, grouped.size());
assertEquals(2, grouped.get("test.example.com").size());
assertEquals(1, grouped.get("www.example.com").size());
}
@Test
void testGroupRecordsByFqdn_NullInput() {
Map<String, List<RecordEntity>> grouped = CfDnsClient.groupRecordsByFqdn(null);
assertNotNull(grouped);
assertTrue(grouped.isEmpty());
}
@Test
void testZoneList() throws Exception {
// Create mock zone response
ZoneMultipleResponse mockResponse = new ZoneMultipleResponse();
ZoneEntity zone1 = new ZoneEntity();
zone1.setId("zone1");
zone1.setName("example.com");
ZoneEntity zone2 = new ZoneEntity();
zone2.setId("zone2");
zone2.setName("test.com");
mockResponse.setResult(List.of(zone1, zone2));
ResponseResultInfo resultInfo = new ResponseResultInfo();
resultInfo.setSuccess(true);
mockResponse.setResponseResultInfo(resultInfo);
// Mock the HTTP client via spy
CfDnsClient spyClient = spy(client);
doReturn(mockResponse).when(spyClient).getRequest(anyString(), eq(ZoneMultipleResponse.class));
List<ZoneEntity> zones = spyClient.zoneList();
assertNotNull(zones);
assertEquals(2, zones.size());
assertEquals("example.com", zones.get(0).getName());
assertEquals("test.com", zones.get(1).getName());
}
@Test
void testZoneGet() throws Exception {
// Create mock zone response
ZoneMultipleResponse mockResponse = new ZoneMultipleResponse();
ZoneEntity zone = new ZoneEntity();
zone.setId(TEST_ZONE_ID);
zone.setName(TEST_ZONE_NAME);
mockResponse.setResult(List.of(zone));
ResponseResultInfo resultInfo = new ResponseResultInfo();
resultInfo.setSuccess(true);
mockResponse.setResponseResultInfo(resultInfo);
CfDnsClient spyClient = spy(client);
doReturn(mockResponse).when(spyClient).getRequest(anyString(), eq(ZoneMultipleResponse.class));
ZoneEntity result = spyClient.zoneGet(TEST_ZONE_NAME);
assertNotNull(result);
assertEquals(TEST_ZONE_ID, result.getId());
assertEquals(TEST_ZONE_NAME, result.getName());
}
@Test
void testZoneOperations() throws Exception {
// Create mock zone response
ZoneMultipleResponse mockResponse = new ZoneMultipleResponse();
ZoneEntity zone = new ZoneEntity();
zone.setId(TEST_ZONE_ID);
zone.setName(TEST_ZONE_NAME);
mockResponse.setResult(List.of(zone));
ResponseResultInfo resultInfo = new ResponseResultInfo();
resultInfo.setSuccess(true);
mockResponse.setResponseResultInfo(resultInfo);
CfDnsClient spyClient = spy(client);
doReturn(mockResponse).when(spyClient).getRequest(anyString(), eq(ZoneMultipleResponse.class));
ZoneOperations ops = spyClient.zone(TEST_ZONE_NAME);
assertNotNull(ops);
}
@Test
void testRecordList_Zone() throws Exception {
ZoneEntity zone = new ZoneEntity();
zone.setId(TEST_ZONE_ID);
zone.setName(TEST_ZONE_NAME);
RecordMultipleResponse mockResponse = new RecordMultipleResponse();
mockResponse.setResultInfo(createResultInfo(1));
RecordEntity rec1 = RecordEntity.build("test.example.com", RecordType.A, 300, "1.2.3.4");
RecordEntity rec2 = RecordEntity.build("www.example.com", RecordType.A, 300, "1.2.3.5");
mockResponse.setResult(List.of(rec1, rec2));
ResponseResultInfo resultInfo = new ResponseResultInfo();
resultInfo.setSuccess(true);
mockResponse.setResponseResultInfo(resultInfo);
CfDnsClient spyClient = spy(client);
doReturn(mockResponse).when(spyClient).getRequest(anyString(), eq(RecordMultipleResponse.class));
List<RecordEntity> records = spyClient.recordList(zone);
assertNotNull(records);
assertEquals(2, records.size());
assertEquals("1.2.3.4", records.get(0).getContent());
}
@Test
void testRecordList_WithPaging() throws Exception {
ZoneEntity zone = createTestZone();
PagingRequest pagingRequest = PagingRequest.of(10, 1);
RecordMultipleResponse mockResponse = new RecordMultipleResponse();
mockResponse.setResultInfo(createResultInfo(1));
RecordEntity rec1 = RecordEntity.build("test.example.com", RecordType.A, 300, "1.2.3.4");
mockResponse.setResult(List.of(rec1));
mockResponse.setResponseResultInfo(createSuccessResultInfo());
CfDnsClient spyClient = spy(client);
doReturn(mockResponse).when(spyClient).getRequest(anyString(), eq(RecordMultipleResponse.class));
List<RecordEntity> records = spyClient.recordList(zone, pagingRequest);
assertNotNull(records);
assertEquals(1, records.size());
}
@Test
void testRecordList_BySld() throws Exception {
ZoneEntity zone = createTestZone();
RecordMultipleResponse mockResponse = new RecordMultipleResponse();
mockResponse.setResultInfo(createResultInfo(1));
RecordEntity rec1 = RecordEntity.build("test.example.com", RecordType.A, 300, "1.2.3.4");
mockResponse.setResult(List.of(rec1));
mockResponse.setResponseResultInfo(createSuccessResultInfo());
CfDnsClient spyClient = spy(client);
doReturn(mockResponse).when(spyClient).getRequest(anyString(), eq(RecordMultipleResponse.class));
List<RecordEntity> records = spyClient.recordList(zone, "test");
assertNotNull(records);
assertEquals(1, records.size());
assertEquals(TEST_ZONE_ID, records.get(0).getZoneId());
}
@Test
void testRecordList_BySldAndType() throws Exception {
ZoneEntity zone = createTestZone();
RecordMultipleResponse mockResponse = new RecordMultipleResponse();
mockResponse.setResultInfo(createResultInfo(1));
RecordEntity rec1 = RecordEntity.build("test.example.com", RecordType.A, 300, "1.2.3.4");
RecordEntity rec2 = RecordEntity.build("test.example.com", RecordType.AAAA, 300, "::1");
mockResponse.setResult(List.of(rec1, rec2));
mockResponse.setResponseResultInfo(createSuccessResultInfo());
CfDnsClient spyClient = spy(client);
doReturn(mockResponse).when(spyClient).getRequest(anyString(), eq(RecordMultipleResponse.class));
List<RecordEntity> records = spyClient.recordList(zone, "test", RecordType.A);
assertNotNull(records);
assertEquals(1, records.size());
assertEquals(RecordType.A, RecordType.valueOf(records.get(0).getType()));
}
@Test
void testRecordList_ByType() throws Exception {
ZoneEntity zone = createTestZone();
RecordMultipleResponse mockResponse = new RecordMultipleResponse();
mockResponse.setResultInfo(createResultInfo(1));
RecordEntity rec1 = RecordEntity.build("test.example.com", RecordType.A, 300, "1.2.3.4");
RecordEntity rec2 = RecordEntity.build("www.example.com", RecordType.AAAA, 300, "::1");
mockResponse.setResult(List.of(rec1, rec2));
mockResponse.setResponseResultInfo(createSuccessResultInfo());
CfDnsClient spyClient = spy(client);
doReturn(mockResponse).when(spyClient).getRequest(anyString(), eq(RecordMultipleResponse.class));
List<RecordEntity> records = spyClient.recordList(zone, RecordType.A);
assertNotNull(records);
assertEquals(1, records.size());
assertEquals(RecordType.A, RecordType.valueOf(records.get(0).getType()));
}
@Test
void testRecordCreateSld() throws Exception {
ZoneEntity zone = createTestZone();
RecordSingleResponse mockResponse = new RecordSingleResponse();
RecordEntity createdRecord = RecordEntity.build("test.example.com", RecordType.A, 300, "1.2.3.4");
createdRecord.setId(TEST_RECORD_ID);
mockResponse.setResult(createdRecord);
mockResponse.setResponseResultInfo(createSuccessResultInfo());
CfDnsClient spyClient = spy(client);
doReturn(mockResponse).when(spyClient).postRequest(anyString(), any(), eq(RecordSingleResponse.class));
RecordEntity result = spyClient.recordCreate(zone, "test.example.com", 300, RecordType.A, "1.2.3.4");
assertNotNull(result);
assertEquals(TEST_RECORD_ID, result.getId());
assertEquals(TEST_ZONE_ID, result.getZoneId());
assertEquals("1.2.3.4", result.getContent());
}
@Test
void testRecordDelete() throws Exception {
ZoneEntity zone = createTestZone();
RecordSingleResponse mockResponse = new RecordSingleResponse();
RecordEntity deletedRecord = RecordEntity.build("test.example.com", RecordType.A, 300, "1.2.3.4");
deletedRecord.setId(TEST_RECORD_ID);
mockResponse.setResult(deletedRecord);
mockResponse.setResponseResultInfo(createSuccessResultInfo());
CfDnsClient spyClient = spy(client);
doReturn(mockResponse).when(spyClient).deleteRequest(anyString(), eq(RecordSingleResponse.class));
boolean result = spyClient.recordDelete(zone, TEST_RECORD_ID);
assertTrue(result);
}
@Test
void testRecordUpdate() throws Exception {
ZoneEntity zone = createTestZone();
RecordEntity record = RecordEntity.build("test.example.com", RecordType.A, 300, "1.2.3.4");
record.setId(TEST_RECORD_ID);
RecordSingleResponse mockResponse = new RecordSingleResponse();
RecordEntity updatedRecord = RecordEntity.build("test.example.com", RecordType.A, 300, "1.2.3.5");
updatedRecord.setId(TEST_RECORD_ID);
mockResponse.setResult(updatedRecord);
mockResponse.setResponseResultInfo(createSuccessResultInfo());
CfDnsClient spyClient = spy(client);
doReturn(mockResponse).when(spyClient).patchRequest(anyString(), any(), eq(RecordSingleResponse.class));
RecordEntity result = spyClient.recordUpdate(zone, record);
assertNotNull(result);
assertEquals(TEST_RECORD_ID, result.getId());
}
@Test
void testRecordDeleteTypeIfExists() throws Exception {
ZoneEntity zone = createTestZone();
RecordMultipleResponse listResponse = new RecordMultipleResponse();
listResponse.setResultInfo(createResultInfo(1));
RecordEntity rec1 = RecordEntity.build("test.example.com", RecordType.A, 300, "1.2.3.4");
rec1.setId(TEST_RECORD_ID);
listResponse.setResult(List.of(rec1));
listResponse.setResponseResultInfo(createSuccessResultInfo());
RecordSingleResponse deleteResponse = new RecordSingleResponse();
RecordEntity deletedRecord = RecordEntity.build("test.example.com", RecordType.A, 300, "1.2.3.4");
deletedRecord.setId(TEST_RECORD_ID);
deleteResponse.setResult(deletedRecord);
deleteResponse.setResponseResultInfo(createSuccessResultInfo());
CfDnsClient spyClient = spy(client);
doReturn(listResponse).when(spyClient).getRequest(anyString(), eq(RecordMultipleResponse.class));
doReturn(deleteResponse).when(spyClient).deleteRequest(anyString(), eq(RecordSingleResponse.class));
// Should not throw exception
spyClient.recordDeleteTypeIfExists(zone, "test", RecordType.A);
verify(spyClient, times(1)).getRequest(anyString(), eq(RecordMultipleResponse.class));
verify(spyClient, times(1)).deleteRequest(anyString(), eq(RecordSingleResponse.class));
}
@Test
void testRecordDeleteTypeIfExists_NotFound() throws Exception {
ZoneEntity zone = createTestZone();
CfDnsClient spyClient = spy(client);
doThrow(new CloudflareNotFoundException("Not found")).when(spyClient).recordList(any(), anyString(), any());
// Should not throw exception when record doesn't exist
assertDoesNotThrow(() -> spyClient.recordDeleteTypeIfExists(zone, "test", RecordType.A));
}
@Test
void testRecordBatch() throws Exception {
ZoneEntity zone = createTestZone();
RecordEntity postRecord = RecordEntity.build("new.example.com", RecordType.A, 300, "1.2.3.4");
RecordEntity patchRecord = RecordEntity.build(TEST_RECORD_ID, "1.2.3.5");
RecordEntity deleteRecord = RecordEntity.build("old.example.com", RecordType.A, 300, "1.2.3.6");
deleteRecord.setId("rec999");
BatchResponse mockResponse = createBatchResponse();
BatchEntry resultEntry = new BatchEntry();
resultEntry.setPosts(List.of(postRecord));
resultEntry.setPatches(List.of(patchRecord));
mockResponse.setResult(resultEntry);
mockResponse.setResponseResultInfo(createSuccessResultInfo());
CfDnsClient spyClient = spy(client);
doReturn(mockResponse).when(spyClient).postRequest(anyString(), any(), eq(BatchResponse.class));
BatchEntry result = spyClient.recordBatch(zone,
List.of(postRecord),
null,
List.of(patchRecord),
List.of(deleteRecord));
assertNotNull(result);
assertNotNull(result.getPosts());
assertEquals(1, result.getPosts().size());
assertEquals(TEST_ZONE_ID, result.getPosts().get(0).getZoneId());
}
}
@@ -27,7 +27,7 @@ public class CfRequestTest {
@Test
public void testBuildRecordInfoName() {
String result = CfRequest.RECORD_INFO_NAME.buildPath("zone123", "sub.domain.com");
String result = CfRequest.RECORD_LIST_NAME.buildPath("zone123", "sub.domain.com");
assertEquals("/zones/zone123/dns_records?name=sub.domain.com", result);
}
@@ -45,7 +45,7 @@ public class CfRequestTest {
@Test
public void testBuildRecordInfo() {
String result = CfRequest.RECORD_INFO_NAME.buildPath("zone123", "sld.domain.com");
String result = CfRequest.RECORD_LIST_NAME.buildPath("zone123", "sld.domain.com");
assertEquals("/zones/zone123/dns_records?name=sld.domain.com", result);
}
@@ -0,0 +1,248 @@
package codes.thischwa.cf.fluent;
import codes.thischwa.cf.CfDnsClient;
import codes.thischwa.cf.CloudflareApiException;
import codes.thischwa.cf.model.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
/**
* Unit tests for the Fluent API package (ZoneOperations and RecordOperations).
*/
class FluentApiTest {
private CfDnsClient mockClient;
private ZoneEntity testZone;
private static final String TEST_ZONE_ID = "zone123";
private static final String TEST_ZONE_NAME = "example.com";
private static final String TEST_SLD = "test";
private static final String TEST_RECORD_ID = "rec123";
@BeforeEach
void setUp() {
mockClient = mock(CfDnsClient.class);
testZone = new ZoneEntity();
testZone.setId(TEST_ZONE_ID);
testZone.setName(TEST_ZONE_NAME);
}
@Test
void testZoneOperations_GetRecord() throws CloudflareApiException {
ZoneOperations zoneOps = new ZoneOperationsImpl(mockClient, testZone);
RecordOperations recordOps = zoneOps.getRecord(TEST_SLD);
assertNotNull(recordOps);
assertInstanceOf(RecordOperationsImpl.class, recordOps);
}
@Test
void testZoneOperations_GetRecordWithTypes() throws CloudflareApiException {
ZoneOperations zoneOps = new ZoneOperationsImpl(mockClient, testZone);
RecordOperations recordOps = zoneOps.getRecord(TEST_SLD, RecordType.A, RecordType.AAAA);
assertNotNull(recordOps);
assertInstanceOf(RecordOperationsImpl.class, recordOps);
}
@Test
void testZoneOperations_List() throws CloudflareApiException {
RecordEntity rec1 = RecordEntity.build("test.example.com", RecordType.A, 300, "1.2.3.4");
RecordEntity rec2 = RecordEntity.build("www.example.com", RecordType.A, 300, "1.2.3.5");
List<RecordEntity> expectedRecords = List.of(rec1, rec2);
when(mockClient.recordList(eq(testZone), any(RecordType[].class)))
.thenReturn(expectedRecords);
ZoneOperations zoneOps = new ZoneOperationsImpl(mockClient, testZone);
List<RecordEntity> result = zoneOps.list();
assertNotNull(result);
assertEquals(2, result.size());
verify(mockClient, times(1)).recordList(eq(testZone), any(RecordType[].class));
}
@Test
void testZoneOperations_ListWithTypes() throws CloudflareApiException {
RecordEntity rec1 = RecordEntity.build("test.example.com", RecordType.A, 300, "1.2.3.4");
List<RecordEntity> expectedRecords = List.of(rec1);
when(mockClient.recordList(eq(testZone), any(RecordType[].class)))
.thenReturn(expectedRecords);
ZoneOperations zoneOps = new ZoneOperationsImpl(mockClient, testZone);
List<RecordEntity> result = zoneOps.list(RecordType.A);
assertNotNull(result);
assertEquals(1, result.size());
verify(mockClient, times(1)).recordList(eq(testZone), any(RecordType[].class));
}
@Test
void testRecordOperations_Get() throws CloudflareApiException {
RecordEntity rec1 = RecordEntity.build("test.example.com", RecordType.A, 300, "1.2.3.4");
List<RecordEntity> expectedRecords = List.of(rec1);
when(mockClient.recordList(eq(testZone), eq(TEST_SLD), any()))
.thenReturn(expectedRecords);
RecordOperations recordOps = new RecordOperationsImpl(mockClient, testZone, TEST_SLD, null);
List<RecordEntity> result = recordOps.get();
assertNotNull(result);
assertEquals(1, result.size());
assertEquals("1.2.3.4", result.get(0).getContent());
verify(mockClient, times(1)).recordList(eq(testZone), eq(TEST_SLD), any());
}
@Test
void testRecordOperations_GetWithTypes() throws CloudflareApiException {
RecordEntity rec1 = RecordEntity.build("test.example.com", RecordType.A, 300, "1.2.3.4");
List<RecordEntity> expectedRecords = List.of(rec1);
RecordType[] types = {RecordType.A};
when(mockClient.recordList(eq(testZone), eq(TEST_SLD), eq(types)))
.thenReturn(expectedRecords);
RecordOperations recordOps = new RecordOperationsImpl(mockClient, testZone, TEST_SLD, types);
List<RecordEntity> result = recordOps.get();
assertNotNull(result);
assertEquals(1, result.size());
verify(mockClient, times(1)).recordList(eq(testZone), eq(TEST_SLD), eq(types));
}
@Test
void testRecordOperations_Create() throws CloudflareApiException {
RecordEntity createdRecord = RecordEntity.build("test.example.com", RecordType.A, 300, "1.2.3.4");
createdRecord.setId(TEST_RECORD_ID);
when(mockClient.recordCreateSld(eq(testZone), eq(TEST_SLD), eq(300), eq(RecordType.A), eq("1.2.3.4")))
.thenReturn(createdRecord);
RecordOperations recordOps = new RecordOperationsImpl(mockClient, testZone, TEST_SLD, null);
RecordEntity result = recordOps.create(RecordType.A, "1.2.3.4", 300);
assertNotNull(result);
assertEquals(TEST_RECORD_ID, result.getId());
assertEquals("1.2.3.4", result.getContent());
verify(mockClient, times(1)).recordCreateSld(eq(testZone), eq(TEST_SLD), eq(300), eq(RecordType.A), eq("1.2.3.4"));
}
@Test
void testRecordOperations_Update_Success() throws CloudflareApiException {
RecordEntity existingRecord = RecordEntity.build("test.example.com", RecordType.A, 300, "1.2.3.4");
existingRecord.setId(TEST_RECORD_ID);
RecordEntity updatedRecord = RecordEntity.build("test.example.com", RecordType.A, 300, "1.2.3.5");
updatedRecord.setId(TEST_RECORD_ID);
when(mockClient.recordList(eq(testZone), eq(TEST_SLD), any()))
.thenReturn(List.of(existingRecord));
when(mockClient.recordUpdate(eq(testZone), any(RecordEntity.class)))
.thenReturn(updatedRecord);
RecordOperations recordOps = new RecordOperationsImpl(mockClient, testZone, TEST_SLD, null);
RecordEntity result = recordOps.update("1.2.3.5");
assertNotNull(result);
assertEquals("1.2.3.5", result.getContent());
verify(mockClient, times(1)).recordList(eq(testZone), eq(TEST_SLD), any());
verify(mockClient, times(1)).recordUpdate(eq(testZone), any(RecordEntity.class));
}
@Test
void testRecordOperations_Update_NoRecordsFound() throws CloudflareApiException {
when(mockClient.recordList(eq(testZone), eq(TEST_SLD), any()))
.thenReturn(List.of());
RecordOperations recordOps = new RecordOperationsImpl(mockClient, testZone, TEST_SLD, null);
CloudflareApiException exception = assertThrows(CloudflareApiException.class, () -> {
recordOps.update("1.2.3.5");
});
assertTrue(exception.getMessage().contains("No recs found"));
verify(mockClient, times(1)).recordList(eq(testZone), eq(TEST_SLD), any());
verify(mockClient, never()).recordUpdate(any(), any());
}
@Test
void testRecordOperations_Update_MultipleRecordsFound() throws CloudflareApiException {
RecordEntity rec1 = RecordEntity.build("test.example.com", RecordType.A, 300, "1.2.3.4");
RecordEntity rec2 = RecordEntity.build("test.example.com", RecordType.AAAA, 300, "::1");
when(mockClient.recordList(eq(testZone), eq(TEST_SLD), any()))
.thenReturn(List.of(rec1, rec2));
RecordOperations recordOps = new RecordOperationsImpl(mockClient, testZone, TEST_SLD, null);
CloudflareApiException exception = assertThrows(CloudflareApiException.class, () -> {
recordOps.update("1.2.3.5");
});
assertTrue(exception.getMessage().contains("Multiple recs found"));
verify(mockClient, times(1)).recordList(eq(testZone), eq(TEST_SLD), any());
verify(mockClient, never()).recordUpdate(any(), any());
}
@Test
void testRecordOperations_Delete() throws CloudflareApiException {
doNothing().when(mockClient).recordDeleteTypeIfExists(eq(testZone), eq(TEST_SLD), any(RecordType[].class));
RecordOperations recordOps = new RecordOperationsImpl(mockClient, testZone, TEST_SLD, null);
recordOps.delete(RecordType.A, RecordType.AAAA);
verify(mockClient, times(1)).recordDeleteTypeIfExists(eq(testZone), eq(TEST_SLD), any(RecordType[].class));
}
@Test
void testRecordOperations_DeleteSingleType() throws CloudflareApiException {
doNothing().when(mockClient).recordDeleteTypeIfExists(eq(testZone), eq(TEST_SLD), any(RecordType[].class));
RecordOperations recordOps = new RecordOperationsImpl(mockClient, testZone, TEST_SLD, null);
recordOps.delete(RecordType.A);
verify(mockClient, times(1)).recordDeleteTypeIfExists(eq(testZone), eq(TEST_SLD), any(RecordType[].class));
}
@Test
void testFluentApiChaining() throws CloudflareApiException {
// Test that fluent API chaining works correctly
RecordEntity createdRecord = RecordEntity.build("test.example.com", RecordType.A, 300, "1.2.3.4");
createdRecord.setId(TEST_RECORD_ID);
when(mockClient.recordCreateSld(eq(testZone), eq(TEST_SLD), eq(300), eq(RecordType.A), eq("1.2.3.4")))
.thenReturn(createdRecord);
ZoneOperations zoneOps = new ZoneOperationsImpl(mockClient, testZone);
RecordEntity result = zoneOps.getRecord(TEST_SLD).create(RecordType.A, "1.2.3.4", 300);
assertNotNull(result);
assertEquals(TEST_RECORD_ID, result.getId());
}
@Test
void testConstructorFields() {
// Test that constructor properly initializes fields
RecordType[] types = {RecordType.A, RecordType.AAAA};
RecordOperationsImpl recordOps = new RecordOperationsImpl(mockClient, testZone, TEST_SLD, types);
assertNotNull(recordOps);
}
@Test
void testZoneOperationsImplConstructor() {
ZoneOperationsImpl zoneOps = new ZoneOperationsImpl(mockClient, testZone);
assertNotNull(zoneOps);
}
}
@@ -0,0 +1,47 @@
package codes.thischwa.cf.model;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
public class BatchEntryTest {
@Test
void testBatchEntry() {
BatchEntry entry = new BatchEntry();
assertEquals("", entry.getId());
List<RecordEntity> patches = new ArrayList<>();
List<RecordEntity> posts = new ArrayList<>();
List<RecordEntity> puts = new ArrayList<>();
List<RecordEntity> deletes = new ArrayList<>();
entry.setPatches(patches);
entry.setPosts(posts);
entry.setPuts(puts);
entry.setDeletes(deletes);
assertSame(patches, entry.getPatches());
assertSame(posts, entry.getPosts());
assertSame(puts, entry.getPuts());
assertSame(deletes, entry.getDeletes());
}
@Test
void testLombokMethods() {
BatchEntry entry1 = new BatchEntry();
BatchEntry entry2 = new BatchEntry();
assertEquals(entry1, entry2);
assertEquals(entry1.hashCode(), entry2.hashCode());
List<RecordEntity> patches = List.of(new RecordEntity());
entry1.setPatches(patches);
assertNotEquals(entry1, entry2);
entry2.setPatches(patches);
assertEquals(entry1, entry2);
assertTrue(entry1.toString().contains("patches="));
}
}
@@ -7,15 +7,37 @@ import static org.junit.jupiter.api.Assertions.*;
public class PagingRequestTest {
@Test
public void testBuildPath() {
void testBuildPath() {
String result = PagingRequest.defaultPaging().addQueryString("/zones");
assertEquals("/zones?page=1&perPage=5000000", result);
assertEquals("/zones?page=1&per_page=1000", result);
}
@Test
public void testBuildPathAdditional() {
void testBuildPathAdditional() {
String result = new PagingRequest( 10, 100).addQueryString("/zones?foo=bar");
assertEquals("/zones?foo=bar&page=10&perPage=100", result);
assertEquals("/zones?foo=bar&page=10&per_page=100", result);
}
@Test
void testGetPagingParams() {
PagingRequest request = PagingRequest.of(2, 50);
java.util.Map<String, String> params = request.getPagingParams();
assertEquals("2", params.get("page"));
assertEquals("50", params.get("perPage"));
}
@Test
void testLombokMethods() {
PagingRequest req1 = PagingRequest.of(1, 10);
PagingRequest req2 = PagingRequest.of(1, 10);
assertEquals(req1, req2);
assertEquals(req1.hashCode(), req2.hashCode());
assertTrue(req1.toString().contains("page=1"));
req1.setPage(5);
assertEquals(5, req1.getPage());
req1.setPerPage(20);
assertEquals(20, req1.getPerPage());
}
}
@@ -0,0 +1,70 @@
package codes.thischwa.cf.model;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class RecordEntityTest {
@Test
void testBuildWithAttributes() {
RecordEntity rec = RecordEntity.build("example.com", RecordType.A, 120, "1.2.3.4");
assertEquals("example.com", rec.getName());
assertEquals("A", rec.getType());
assertEquals(120, rec.getTtl());
assertEquals("1.2.3.4", rec.getContent());
}
@Test
void testBuildWithIdAndContent() {
RecordEntity rec = RecordEntity.build("id-123", "1.2.3.4");
assertEquals("id-123", rec.getId());
assertEquals("1.2.3.4", rec.getContent());
}
@Test
void testBuildWithIdAndAttributes() {
RecordEntity rec = RecordEntity.build("id-123", "example.com", "A", 120, "1.2.3.4");
assertEquals("id-123", rec.getId());
assertEquals("example.com", rec.getName());
assertEquals("A", rec.getType());
assertEquals(120, rec.getTtl());
assertEquals("1.2.3.4", rec.getContent());
}
@Test
void testBuildWithInvalidType() {
assertThrows(IllegalArgumentException.class, () ->
RecordEntity.build("id-123", "example.com", "INVALID", 120, "1.2.3.4")
);
}
@Test
void testGetSld() {
RecordEntity rec = new RecordEntity();
assertNull(rec.getSld());
rec.setName("sub.example.com");
assertEquals("sub", rec.getSld());
rec.setName("example.com");
assertEquals("example", rec.getSld());
rec.setName("host");
assertEquals("host", rec.getSld());
rec.setName(".dotstart");
assertEquals(".dotstart", rec.getSld());
}
@Test
void testGetSldWithZoneName() {
RecordEntity rec = new RecordEntity();
rec.setName("sub.example.com");
rec.setZoneName("example.com");
assertEquals("sub", rec.getSld());
rec.setName("my.sub.example.com");
rec.setZoneName("example.com");
assertEquals("my.sub", rec.getSld());
}
}
@@ -0,0 +1,40 @@
package codes.thischwa.cf.model;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class RecordTypeTest {
@Test
void testGetType() {
assertEquals("A", RecordType.A.getType());
assertEquals("AAAA", RecordType.AAAA.getType());
assertEquals("CNAME", RecordType.CNAME.getType());
assertEquals("TXT", RecordType.TXT.getType());
assertEquals("SRV", RecordType.SRV.getType());
assertEquals("LOC", RecordType.LOC.getType());
assertEquals("MX", RecordType.MX.getType());
assertEquals("NS", RecordType.NS.getType());
assertEquals("CAA", RecordType.CAA.getType());
assertEquals("CERT", RecordType.CERT.getType());
assertEquals("DNSKEY", RecordType.DNSKEY.getType());
assertEquals("DS", RecordType.DS.getType());
assertEquals("NAPTR", RecordType.NAPTR.getType());
assertEquals("SMIMEA", RecordType.SMIMEA.getType());
assertEquals("SSHFP", RecordType.SSHFP.getType());
assertEquals("TLSA", RecordType.TLSA.getType());
assertEquals("URI", RecordType.URI.getType());
}
@Test
void testToString() {
assertEquals("A", RecordType.A.toString());
assertEquals("CNAME", RecordType.CNAME.toString());
}
@Test
void testValueOf() {
assertEquals(RecordType.A, RecordType.valueOf("A"));
assertEquals(RecordType.CNAME, RecordType.valueOf("CNAME"));
}
}
@@ -0,0 +1,41 @@
package codes.thischwa.cf.model;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import java.time.LocalDateTime;
import java.util.Set;
import org.junit.jupiter.api.Test;
public class ZoneEntityTest {
@Test
void testZoneEntity() {
ZoneEntity zone = new ZoneEntity();
zone.setId("zone-id");
zone.setName("example.com");
zone.setDevelopmentMode(7200);
Set<String> ns = Set.of("ns1.cloudflare.com", "ns2.cloudflare.com");
zone.setNameServers(ns);
zone.setOriginalNameServers(ns);
LocalDateTime now = LocalDateTime.now();
zone.setCreatedOn(now);
zone.setModifiedOn(now);
zone.setActivatedOn(now);
zone.setStatus("active");
zone.setPaused(false);
zone.setType("full");
assertEquals("zone-id", zone.getId());
assertEquals("example.com", zone.getName());
assertEquals(7200, zone.getDevelopmentMode());
assertEquals(ns, zone.getNameServers());
assertEquals(ns, zone.getOriginalNameServers());
assertEquals(now, zone.getCreatedOn());
assertEquals(now, zone.getModifiedOn());
assertEquals(now, zone.getActivatedOn());
assertEquals("active", zone.getStatus());
assertFalse(zone.getPaused());
assertEquals("full", zone.getType());
}
}
+1 -1
View File
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<configuration debug="true">
<appender name="current"
class="ch.qos.logback.core.ConsoleAppender">