refactor: make PagingRequest an immutable record
Build and Analyse / build-and-analyse (push) Failing after 1m17s

- Replace Lombok-based PagingRequest with an immutable record (page(), perPage())
- Centralize paging limits (DEFAULT_PAGE_SIZE, MAX_RECORDS_PER_PAGE, MIN/MAX_ZONES_PER_PAGE)
- Add forRecords(), forZones(), defaultPaging(), next() and withPage(); remove setters and getPagingParams()
- Include invalid values in validation messages, reject null endpoints in addQueryString()
- Use an internal page size of 1000 when fetching all DNS records
- Adapt CfDnsClient, tests, README and changelog

Co-authored-by: Junie <junie@jetbrains.com>
This commit is contained in:
thischwaandJunie committed 2026-11-07 11:55:12 +01:00
1 parent 6ab318063f
commit be0512111d
9 files changed
+187 -187

No files matched your search

+7 -6
View File
@@ -99,12 +99,13 @@ Without a `PagingRequest`, `zoneList()` fetches zones in pages of 50, requesting
Use a `PagingRequest` to retrieve a specific page: Use a `PagingRequest` to retrieve a specific page:
```java ```java
List<ZoneEntity> zones = cfDnsClient.zoneList(PagingRequest.of(1, 50)); // page 1, 50 zones per page List<ZoneEntity> zones = cfDnsClient.zoneList(PagingRequest.forZones(1, 50)); // page 1, 50 zones per page
``` ```
Page numbers start at 1. Cloudflare accepts page sizes from 5 to 50 for zones and from 1 to 5,000,000 Page numbers start at 1. `PagingRequest` is immutable; use `forRecords(page, perPage)` for DNS records and
for DNS records. `PagingRequest.defaultPaging()` requests page 1 with 50 items; it does not fetch `forZones(page, perPage)` for zones. Cloudflare accepts page sizes from 5 to 50 for zones and from
additional pages. 1 to 5,000,000 for DNS records. `PagingRequest.defaultPaging()` requests page 1 with 50 items; it
does not fetch additional pages. Use `next()` or `withPage(page)` to create another page request.
--- ---
@@ -165,10 +166,10 @@ If exactly one record type is given, the filtering is done by Cloudflare, otherw
List<RecordEntity> allZoneRecords = cfDnsClient.recordList(zone); List<RecordEntity> allZoneRecords = cfDnsClient.recordList(zone);
// Get the records of a zone page by page (page 2, 100 records per page) // Get the records of a zone page by page (page 2, 100 records per page)
List<RecordEntity> pagedRecords = cfDnsClient.recordList(zone, PagingRequest.of(2, 100)); List<RecordEntity> pagedRecords = cfDnsClient.recordList(zone, PagingRequest.forRecords(2, 100));
``` ```
Without a `PagingRequest`, all pages are fetched using up to 5,000,000 records per page and combined into one result. Without a `PagingRequest`, all pages are fetched using 1,000 records per page and combined into one result.
This large page size can consume substantial memory. If paging remains inconsistent after three attempts, the client logs a warning and may return an incomplete list. Use a smaller `PagingRequest` to retrieve one page at a time; further pages must be requested explicitly. This large page size can consume substantial memory. If paging remains inconsistent after three attempts, the client logs a warning and may return an incomplete list. Use a smaller `PagingRequest` to retrieve one page at a time; further pages must be requested explicitly.
With a `PagingRequest`, exactly the requested page is returned. With a `PagingRequest`, exactly the requested page is returned.
+2 -1
View File
@@ -7,6 +7,7 @@
- `recordList(zone, RecordType... types)` → `recordListByType(zone, types...)` - `recordList(zone, RecordType... types)` → `recordListByType(zone, types...)`
- `recordList(zone)` and `recordList(zone, PagingRequest)` remain unchanged - `recordList(zone)` and `recordList(zone, PagingRequest)` remain unchanged
- `CfDnsClient#recordCreateSld(...)` was removed; use `recordCreateSubdomain(...)` - `CfDnsClient#recordCreateSld(...)` was removed; use `recordCreateSubdomain(...)`
- `PagingRequest` is now an immutable record with `page()` and `perPage()` accessors. The setters and `getPagingParams()` were removed; use `forRecords(...)`, `forZones(...)`, `next()` and `withPage(...)` instead.
- `PagingRequest.defaultPaging()` now requests 50 items instead of 1,000. Page numbers and page sizes are validated; zone requests accept 5–50 items per page, while DNS record requests accept 1–5,000,000. - `PagingRequest.defaultPaging()` now requests 50 items instead of 1,000. Page numbers and page sizes are validated; zone requests accept 5–50 items per page, while DNS record requests accept 1–5,000,000.
- `withBaseUrl` only accepts HTTPS URLs (plain HTTP only for loopback hosts like `localhost`), otherwise an `IllegalArgumentException` is thrown - `withBaseUrl` only accepts HTTPS URLs (plain HTTP only for loopback hosts like `localhost`), otherwise an `IllegalArgumentException` is thrown
- `build()` throws an `IllegalStateException` if no authentication was configured, `null` credentials throw an `IllegalArgumentException` - `build()` throws an `IllegalStateException` if no authentication was configured, `null` credentials throw an `IllegalArgumentException`
@@ -31,7 +32,7 @@
- fixed: API errors were wrapped into a generic "Unexpected error!" exception - fixed: API errors were wrapped into a generic "Unexpected error!" exception
- fixed: `zoneGet` threw an `IndexOutOfBoundsException` for unknown zones, it now returns `null` or throws a `CloudflareNotFoundException` (depending on `emptyResultThrowsException`) - fixed: `zoneGet` threw an `IndexOutOfBoundsException` for unknown zones, it now returns `null` or throws a `CloudflareNotFoundException` (depending on `emptyResultThrowsException`)
- fixed: `getSubdomain()` failed for apex records and records with multi-level subdomains, batch operations now send the full record name - fixed: `getSubdomain()` failed for apex records and records with multi-level subdomains, batch operations now send the full record name
- fixed: `zoneList()` and `recordList(...)` without `PagingRequest` returned only the first page, now all pages are fetched; `recordList(zone, null)` uses the maximum DNS page size of 5,000,000 - fixed: `zoneList()` and `recordList(...)` without `PagingRequest` returned only the first page, now all pages are fetched; `recordList(zone, null)` uses a page size of 1,000 to limit response memory use
- fixed: DNS records are listed with a stable order (`order=name`), because without it Cloudflare's pages can overlap and miss records; fetched records are de-duplicated and inconsistent pages are fetched again - fixed: DNS records are listed with a stable order (`order=name`), because without it Cloudflare's pages can overlap and miss records; fetched records are de-duplicated and inconsistent pages are fetched again
- fixed: `recordDelete` threw a `NullPointerException` for an empty result - fixed: `recordDelete` threw a `NullPointerException` for an empty result
- 0.5.0: - 0.5.0:
@@ -87,17 +87,10 @@ import org.jetbrains.annotations.Nullable;
@Slf4j @Slf4j
public class CfDnsClient extends CfBasicHttpClient { public class CfDnsClient extends CfBasicHttpClient {
/**
* Page size used when fetching all zones. Cloudflare allows 5 to 50 zones per page.
*/
static final int ZONES_PER_PAGE = 50;
private static final int MIN_ZONES_PER_PAGE = 5;
/** /**
* Page size used when fetching all DNS records. * Page size used when fetching all DNS records.
*/ */
static final int MAX_RECORDS_PER_PAGE = 1000; static final int RECORDS_PER_PAGE = 1000;
/** /**
* Sort order for listing DNS records. Cloudflare doesn't guarantee a stable order without it, * Sort order for listing DNS records. Cloudflare doesn't guarantee a stable order without it,
@@ -131,7 +124,7 @@ public class CfDnsClient extends CfBasicHttpClient {
* @param auth The authentication mechanism to use (ApiTokenAuth or EmailKeyAuth) * @param auth The authentication mechanism to use (ApiTokenAuth or EmailKeyAuth)
*/ */
CfDnsClient(boolean emptyResultThrowsException, String baseUrl, CfDnsClientBuilder.CfAuth auth) { CfDnsClient(boolean emptyResultThrowsException, String baseUrl, CfDnsClientBuilder.CfAuth auth) {
this(emptyResultThrowsException, baseUrl, auth, MAX_RECORDS_PER_PAGE); this(emptyResultThrowsException, baseUrl, auth, RECORDS_PER_PAGE);
} }
/** /**
@@ -235,7 +228,8 @@ public class CfDnsClient extends CfBasicHttpClient {
* @throws CloudflareApiException If an error occurs during the API request or response handling. * @throws CloudflareApiException If an error occurs during the API request or response handling.
*/ */
public List<ZoneEntity> zoneList() throws CloudflareApiException { public List<ZoneEntity> zoneList() throws CloudflareApiException {
return getAllPages(CfRequest.ZONE_LIST.buildPath(), ZoneMultipleResponse.class, ZONES_PER_PAGE); return getAllPages(CfRequest.ZONE_LIST.buildPath(), ZoneMultipleResponse.class,
PagingRequest.DEFAULT_PAGE_SIZE);
} }
/** /**
@@ -250,10 +244,13 @@ public class CfDnsClient extends CfBasicHttpClient {
* @throws IllegalArgumentException if the page size is outside the range 5 to 50 * @throws IllegalArgumentException if the page size is outside the range 5 to 50
*/ */
public List<ZoneEntity> zoneList(PagingRequest pagingRequest) throws CloudflareApiException { public List<ZoneEntity> zoneList(PagingRequest pagingRequest) throws CloudflareApiException {
if (pagingRequest.getPerPage() < MIN_ZONES_PER_PAGE Objects.requireNonNull(pagingRequest, "pagingRequest must not be null");
|| pagingRequest.getPerPage() > ZONES_PER_PAGE) { int perPage = pagingRequest.perPage();
throw new IllegalArgumentException("Zone page size must be between " + MIN_ZONES_PER_PAGE if (perPage < PagingRequest.MIN_ZONES_PER_PAGE
+ " and " + ZONES_PER_PAGE); || perPage > PagingRequest.MAX_ZONES_PER_PAGE) {
throw new IllegalArgumentException("Zone page size must be between "
+ PagingRequest.MIN_ZONES_PER_PAGE + " and " + PagingRequest.MAX_ZONES_PER_PAGE
+ ", but was " + perPage);
} }
String endpoint = pagingRequest.addQueryString(CfRequest.ZONE_LIST.buildPath()); String endpoint = pagingRequest.addQueryString(CfRequest.ZONE_LIST.buildPath());
ZoneMultipleResponse response = getRequest(endpoint, ZoneMultipleResponse.class); ZoneMultipleResponse response = getRequest(endpoint, ZoneMultipleResponse.class);
@@ -299,7 +296,7 @@ public class CfDnsClient extends CfBasicHttpClient {
* *
* @param zone The zone entity containing information about the target zone. * @param zone The zone entity containing information about the target zone.
* @param pagingRequest The paging request containing parameters such as page size and number. * @param pagingRequest The paging request containing parameters such as page size and number.
* If {@code null}, all pages are fetched using the maximum supported page size. * If {@code null}, all pages are fetched using an internal page size of 1,000.
* For a specific page, Cloudflare allows a page size between 1 and 5,000,000. * For a specific page, Cloudflare allows a page size between 1 and 5,000,000.
* @return A list of RecordEntity objects representing the DNS records of the specified zone. * @return A list of RecordEntity objects representing the DNS records of the specified zone.
* @throws CloudflareApiException If an error occurs during the API request or response processing. * @throws CloudflareApiException If an error occurs during the API request or response processing.
@@ -309,7 +306,7 @@ public class CfDnsClient extends CfBasicHttpClient {
String path = appendQuery(CfRequest.RECORD_LIST.buildPath(zone.getId()), RECORD_ORDER); String path = appendQuery(CfRequest.RECORD_LIST.buildPath(zone.getId()), RECORD_ORDER);
if (pagingRequest == null) { if (pagingRequest == null) {
return filterAndSetZoneRecords(zone, null, return filterAndSetZoneRecords(zone, null,
getAllPages(path, RecordMultipleResponse.class, PagingRequest.MAX_PER_PAGE)); getAllPages(path, RecordMultipleResponse.class, recordsPerPage));
} }
RecordMultipleResponse resp = getRequest(pagingRequest.addQueryString(path), RecordMultipleResponse.class); RecordMultipleResponse resp = getRequest(pagingRequest.addQueryString(path), RecordMultipleResponse.class);
checkResponse(resp); checkResponse(resp);
@@ -682,9 +679,10 @@ public class CfDnsClient extends CfBasicHttpClient {
Map<String, E> byId = new LinkedHashMap<>(); Map<String, E> byId = new LinkedHashMap<>();
List<E> withoutId = new ArrayList<>(); List<E> withoutId = new ArrayList<>();
int expectedCount = -1; int expectedCount = -1;
int page = 1; PagingRequest pagingRequest = new PagingRequest(1, perPage);
while (true) { while (true) {
String pagedEndpoint = PagingRequest.of(page, perPage).addQueryString(endpoint); int page = pagingRequest.page();
String pagedEndpoint = pagingRequest.addQueryString(endpoint);
R resp = getRequest(pagedEndpoint, responseType); R resp = getRequest(pagedEndpoint, responseType);
checkResponse(resp); checkResponse(resp);
List<E> pageResult = resp.getResult(); List<E> pageResult = resp.getResult();
@@ -709,7 +707,7 @@ public class CfDnsClient extends CfBasicHttpClient {
all.addAll(withoutId); all.addAll(withoutId);
return new PagingResult<>(all, info == null || page == 1 ? -1 : expectedCount); return new PagingResult<>(all, info == null || page == 1 ? -1 : expectedCount);
} }
page++; pagingRequest = pagingRequest.next();
} }
} }
@@ -195,7 +195,7 @@ public class CfDnsClientBuilder {
"No authentication configured, use withApiTokenAuth(...) or withEmailKeyAuth(...)"); "No authentication configured, use withApiTokenAuth(...) or withEmailKeyAuth(...)");
} }
String url = baseUrl == null ? DEFAULT_BASEURL : baseUrl; String url = baseUrl == null ? DEFAULT_BASEURL : baseUrl;
return new CfDnsClient(emptyResultThrowsException, url, auth, CfDnsClient.MAX_RECORDS_PER_PAGE, return new CfDnsClient(emptyResultThrowsException, url, auth, CfDnsClient.RECORDS_PER_PAGE,
connectTimeout, responseTimeout); connectTimeout, responseTimeout);
} }
@@ -37,7 +37,7 @@ public interface ZoneOperations {
/** /**
* Lists all DNS records within the zone, optionally filtered by types. * Lists all DNS records within the zone, optionally filtered by types.
* *
* @param types optional DNS record types to filter by * @param types optional DNS record types to filter by
* @return a list of RecordEntity objects matching the criteria * @return a list of RecordEntity objects matching the criteria
* @throws CloudflareApiException if an error occurs while retrieving records * @throws CloudflareApiException if an error occurs while retrieving records
*/ */
@@ -1,130 +1,112 @@
package codes.thischwa.cf.model; package codes.thischwa.cf.model;
import java.util.Map; import java.util.Objects;
import lombok.Data;
/** /**
* Represents a request model for paginated data. * Immutable pagination parameters for Cloudflare list endpoints. Page numbers start at 1.
* *
* <p>This class encapsulates the page number and the number of items per page for a paginated * <p>Use {@link #forZones(int, int)} for zone requests and {@link #forRecords(int, int)} for DNS
* request, along with utility methods for constructing and retrieving pagination parameters. Page * record requests. For example:
* numbers must be at least 1, and page sizes must be between 1 and 5,000,000 for DNS record requests.
* Zone requests have the more restrictive Cloudflare limit of 5 to 50 items per page.
* *
* <p>Key functionalities: * <pre>{@code
* * List<RecordEntity> records = client.recordList(zone, PagingRequest.forRecords(1, 100));
* <ul> * List<ZoneEntity> zones = client.zoneList(PagingRequest.forZones(1, 50));
* <li>Creating a {@code PagingRequest} instance with specific pagination values using the {@code * }</pre>
* of} method.
* <li>Creating a default {@code PagingRequest} with predefined pagination values.
* <li>Retrieving pagination parameters as a key-value map.
* <li>Generating a query string representation for the pagination parameters.
* </ul>
*/ */
@Data public record PagingRequest(int page, int perPage) {
public class PagingRequest {
/**
* Default page size for a single request, which is within the limits for zones and DNS records.
*/
private static final int DEFAULT_PAGE_SIZE = 50;
/** /** Default page size, valid for zones and DNS records. */
* Maximum number of DNS records allowed per page by Cloudflare. public static final int DEFAULT_PAGE_SIZE = 50;
*/
public static final int MAX_PER_PAGE = 5_000_000;
private int page; /** Maximum number of DNS records allowed per page by Cloudflare. */
private int perPage; public static final int MAX_RECORDS_PER_PAGE = 5_000_000;
PagingRequest(int page, int perPage) { /** Minimum number of zones allowed per page by Cloudflare. */
this.page = validatePage(page); public static final int MIN_ZONES_PER_PAGE = 5;
this.perPage = validatePerPage(perPage);
/** Maximum number of zones allowed per page by Cloudflare. */
public static final int MAX_ZONES_PER_PAGE = 50;
/** Validates the page number and page size. */
public PagingRequest {
if (page < 1) {
throw new IllegalArgumentException("page must be at least 1, but was " + page);
}
if (perPage < 1 || perPage > MAX_RECORDS_PER_PAGE) {
throw new IllegalArgumentException("perPage must be between 1 and " + MAX_RECORDS_PER_PAGE
+ ", but was " + perPage);
}
} }
/** /**
* Creates a new {@code PagingRequest} instance with the specified page number and items per page. * Creates pagination parameters for a DNS record request.
* The page must be at least 1, and the page size must be between 1 and 5,000,000. Zone requests
* have a more restrictive page-size range of 5 to 50, enforced by {@code zoneList}.
* *
* @param page the page number to be requested * @param page the 1-based page number
* @param perPage the number of items to be included per page * @param perPage the number of records per page, from 1 to {@value #MAX_RECORDS_PER_PAGE}
* @return a new {@code PagingRequest} instance with the provided parameters * @return the validated pagination request
* @throws IllegalArgumentException if the page or page size is outside the allowed range * @throws IllegalArgumentException if either value is outside its allowed range
*/ */
public static PagingRequest of(int page, int perPage) { public static PagingRequest forRecords(int page, int perPage) {
return new PagingRequest(page, perPage); return new PagingRequest(page, perPage);
} }
/** /**
* Creates a default {@code PagingRequest} instance for page 1 with 50 items per page. This is a * Creates pagination parameters for a zone request.
* request for one page; it does not fetch additional pages.
* *
* @return a default {@code PagingRequest} instance with predefined pagination parameters * @param page the 1-based page number
* @param perPage the number of zones per page, from {@value #MIN_ZONES_PER_PAGE} to
* {@value #MAX_ZONES_PER_PAGE}
* @return the validated pagination request
* @throws IllegalArgumentException if either value is outside its allowed range
*/
public static PagingRequest forZones(int page, int perPage) {
if (perPage < MIN_ZONES_PER_PAGE || perPage > MAX_ZONES_PER_PAGE) {
throw new IllegalArgumentException("Zone page size must be between " + MIN_ZONES_PER_PAGE
+ " and " + MAX_ZONES_PER_PAGE + ", but was " + perPage);
}
return new PagingRequest(page, perPage);
}
/**
* Creates a request for page 1 with {@value #DEFAULT_PAGE_SIZE} items per page.
* This requests one page; it does not fetch additional pages.
*
* @return the default pagination request
*/ */
public static PagingRequest defaultPaging() { public static PagingRequest defaultPaging() {
return new PagingRequest(1, DEFAULT_PAGE_SIZE); return new PagingRequest(1, DEFAULT_PAGE_SIZE);
} }
/** /**
* Sets the page number. * Returns a request for the next page, retaining the current page size.
* *
* @param page the page number, which must be at least 1 * @return the next page request
* @throws IllegalArgumentException if the page number is less than 1
*/ */
public void setPage(int page) { public PagingRequest next() {
this.page = validatePage(page); return new PagingRequest(page + 1, perPage);
} }
/** /**
* Sets the number of items per page. * Returns a copy of this request with the specified page number.
* *
* @param perPage the page size, between 1 and 5,000,000 for DNS record requests * @param page the 1-based page number
* @throws IllegalArgumentException if the page size is outside the allowed range * @return the updated pagination request
*/ */
public void setPerPage(int perPage) { public PagingRequest withPage(int page) {
this.perPage = validatePerPage(perPage); return new PagingRequest(page, perPage);
} }
/** /**
* Retrieves the pagination parameters in a key-value map format. * Appends Cloudflare-compatible pagination parameters ({@code page} and {@code per_page}) to an
* endpoint.
* *
* @return a map containing the pagination parameters, where the key "page" indicates the current * @param endpoint the base URL or API endpoint, optionally containing a query string
* page number and the key "perPage" indicates the number of items per page. The map key is * @return the endpoint with pagination parameters appended
* intentionally named "perPage"; Cloudflare's query parameter is "per_page". Use * @throws NullPointerException if {@code endpoint} is {@code null}
* {@link #addQueryString(String)} to build a Cloudflare-compatible query string.
*/
public Map<String, String> getPagingParams() {
return Map.of("page", String.valueOf(page), "perPage", String.valueOf(perPage));
}
/**
* Appends a query string with pagination parameters ({@code page} and {@code per_page}) to the
* provided endpoint. Unlike {@link #getPagingParams()}, this method uses Cloudflare's
* {@code per_page} query parameter name.
*
* @param endpoint the base URL or API endpoint to which the query string will be appended
* @return the complete URL with the appended query string for pagination
*/ */
public String addQueryString(String endpoint) { public String addQueryString(String endpoint) {
return endpoint + queryString(endpoint.contains("?")); Objects.requireNonNull(endpoint, "endpoint must not be null");
} return endpoint + (endpoint.contains("?") ? "&" : "?")
+ "page=" + page + "&per_page=" + perPage;
private String queryString(boolean add) {
String qs = "page=" + page + "&per_page=" + perPage;
return add ? "&" + qs : "?" + qs;
}
private static int validatePage(int page) {
if (page < 1) {
throw new IllegalArgumentException("page must be at least 1");
}
return page;
}
private static int validatePerPage(int perPage) {
if (perPage < 1 || perPage > MAX_PER_PAGE) {
throw new IllegalArgumentException("perPage must be between 1 and " + MAX_PER_PAGE);
}
return perPage;
} }
} }
@@ -109,7 +109,7 @@ public class CfClientTest {
assertFalse(zones.isEmpty()); assertFalse(zones.isEmpty());
assertEquals(ZONE_STR, zones.get(0).getName()); assertEquals(ZONE_STR, zones.get(0).getName());
zones = client.zoneList(PagingRequest.of(1, 50)); zones = client.zoneList(PagingRequest.forZones(1, 50));
assertNotNull(zones); assertNotNull(zones);
assertFalse(zones.isEmpty()); assertFalse(zones.isEmpty());
assertEquals(ZONE_STR, zones.get(0).getName()); assertEquals(ZONE_STR, zones.get(0).getName());
@@ -502,17 +502,17 @@ public class CfClientTest {
} }
// Test paging with page size of 5 // Test paging with page size of 5
PagingRequest page1Request = PagingRequest.of(1, 5); PagingRequest page1Request = PagingRequest.forRecords(1, 5);
List<RecordEntity> page1Records = client.recordList(zone, page1Request); List<RecordEntity> page1Records = client.recordList(zone, page1Request);
assertEquals(5, page1Records.size(), "First page should contain 5 records"); assertEquals(5, page1Records.size(), "First page should contain 5 records");
// 2nd page should also contain 5 records (if we have at least 12 total) // 2nd page should also contain 5 records (if we have at least 12 total)
PagingRequest page2Request = PagingRequest.of(2, 5); PagingRequest page2Request = PagingRequest.forRecords(2, 5);
List<RecordEntity> page2Records = client.recordList(zone, page2Request); List<RecordEntity> page2Records = client.recordList(zone, page2Request);
assertEquals(5, page2Records.size(), "Second page should contain at least 5 records"); assertEquals(5, page2Records.size(), "Second page should contain at least 5 records");
// 3rd page should contain 2 records // 3rd page should contain 2 records
PagingRequest page3Request = PagingRequest.of(3, 5); PagingRequest page3Request = PagingRequest.forRecords(3, 5);
List<RecordEntity> page3Records = client.recordList(zone, page3Request); List<RecordEntity> page3Records = client.recordList(zone, page3Request);
assertEquals(2, page3Records.size(), "Third page should contain 2 records"); assertEquals(2, page3Records.size(), "Third page should contain 2 records");
@@ -128,8 +128,8 @@ class CfDnsClientMockTest {
CfDnsClient spyClient = spy(client); CfDnsClient spyClient = spy(client);
doReturn(mockResponse).when(spyClient).getRequest(anyString(), eq(ZoneMultipleResponse.class)); doReturn(mockResponse).when(spyClient).getRequest(anyString(), eq(ZoneMultipleResponse.class));
spyClient.zoneList(PagingRequest.of(1, 5)); spyClient.zoneList(PagingRequest.forZones(1, 5));
spyClient.zoneList(PagingRequest.of(1, 50)); spyClient.zoneList(PagingRequest.forZones(1, 50));
verify(spyClient).getRequest(eq("/zones?page=1&per_page=5"), eq(ZoneMultipleResponse.class)); verify(spyClient).getRequest(eq("/zones?page=1&per_page=5"), eq(ZoneMultipleResponse.class));
verify(spyClient).getRequest(eq("/zones?page=1&per_page=50"), eq(ZoneMultipleResponse.class)); verify(spyClient).getRequest(eq("/zones?page=1&per_page=50"), eq(ZoneMultipleResponse.class));
@@ -140,9 +140,9 @@ class CfDnsClientMockTest {
CfDnsClient spyClient = spy(client); CfDnsClient spyClient = spy(client);
assertThrows(IllegalArgumentException.class, assertThrows(IllegalArgumentException.class,
() -> spyClient.zoneList(PagingRequest.of(1, 4))); () -> spyClient.zoneList(new PagingRequest(1, 4)));
assertThrows(IllegalArgumentException.class, assertThrows(IllegalArgumentException.class,
() -> spyClient.zoneList(PagingRequest.of(1, 51))); () -> spyClient.zoneList(new PagingRequest(1, 51)));
verify(spyClient, never()).getRequest(anyString(), eq(ZoneMultipleResponse.class)); verify(spyClient, never()).getRequest(anyString(), eq(ZoneMultipleResponse.class));
} }
@@ -217,7 +217,7 @@ class CfDnsClientMockTest {
@Test @Test
void testRecordList_WithPaging() throws Exception { void testRecordList_WithPaging() throws Exception {
ZoneEntity zone = createTestZone(); ZoneEntity zone = createTestZone();
PagingRequest pagingRequest = PagingRequest.of(10, 1); PagingRequest pagingRequest = PagingRequest.forRecords(10, 1);
RecordMultipleResponse mockResponse = new RecordMultipleResponse(); RecordMultipleResponse mockResponse = new RecordMultipleResponse();
mockResponse.setResultInfo(createResultInfo(1)); mockResponse.setResultInfo(createResultInfo(1));
@@ -484,10 +484,10 @@ class CfDnsClientMockTest {
CfDnsClient spyClient = spy(client); CfDnsClient spyClient = spy(client);
doReturn(zoneResponse(List.of(zone("z1", "a.com"), zone("z2", "b.com")), doReturn(zoneResponse(List.of(zone("z1", "a.com"), zone("z2", "b.com")),
new ResultInfo(1, 2, 2, 2, 3))) new ResultInfo(1, 2, 2, 2, 3)))
.when(spyClient).getRequest(eq("/zones?page=1&per_page=" + CfDnsClient.ZONES_PER_PAGE), .when(spyClient).getRequest(eq("/zones?page=1&per_page=" + PagingRequest.DEFAULT_PAGE_SIZE),
eq(ZoneMultipleResponse.class)); eq(ZoneMultipleResponse.class));
doReturn(zoneResponse(List.of(zone("z3", "c.com")), new ResultInfo(2, 2, 2, 1, 3))) doReturn(zoneResponse(List.of(zone("z3", "c.com")), new ResultInfo(2, 2, 2, 1, 3)))
.when(spyClient).getRequest(eq("/zones?page=2&per_page=" + CfDnsClient.ZONES_PER_PAGE), .when(spyClient).getRequest(eq("/zones?page=2&per_page=" + PagingRequest.DEFAULT_PAGE_SIZE),
eq(ZoneMultipleResponse.class)); eq(ZoneMultipleResponse.class));
List<ZoneEntity> zones = spyClient.zoneList(); List<ZoneEntity> zones = spyClient.zoneList();
@@ -499,7 +499,7 @@ class CfDnsClientMockTest {
@Test @Test
void testRecordListByType_FetchesAllPages() throws Exception { void testRecordListByType_FetchesAllPages() throws Exception {
ZoneEntity zone = createTestZone(); ZoneEntity zone = createTestZone();
String base = "/zones/" + TEST_ZONE_ID + "/dns_records?type=A&order=name&direction=asc&page=%d&per_page=" + CfDnsClient.MAX_RECORDS_PER_PAGE; String base = "/zones/" + TEST_ZONE_ID + "/dns_records?type=A&order=name&direction=asc&page=%d&per_page=" + CfDnsClient.RECORDS_PER_PAGE;
CfDnsClient spyClient = spy(client); CfDnsClient spyClient = spy(client);
doReturn(recordResponse(List.of(RecordEntity.build("a.example.com", RecordType.A, 60, "1.1.1.1")), doReturn(recordResponse(List.of(RecordEntity.build("a.example.com", RecordType.A, 60, "1.1.1.1")),
new ResultInfo(1, 1, 2, 1, 2))) new ResultInfo(1, 1, 2, 1, 2)))
@@ -518,7 +518,7 @@ class CfDnsClientMockTest {
void testRecordListBySld_FetchesAllPages() throws Exception { void testRecordListBySld_FetchesAllPages() throws Exception {
ZoneEntity zone = createTestZone(); ZoneEntity zone = createTestZone();
String base = "/zones/" + TEST_ZONE_ID + "/dns_records?name=test.example.com&order=name&direction=asc&page=%d&per_page=" String base = "/zones/" + TEST_ZONE_ID + "/dns_records?name=test.example.com&order=name&direction=asc&page=%d&per_page="
+ CfDnsClient.MAX_RECORDS_PER_PAGE; + CfDnsClient.RECORDS_PER_PAGE;
CfDnsClient spyClient = spy(client); CfDnsClient spyClient = spy(client);
doReturn(recordResponse(List.of(RecordEntity.build("test.example.com", RecordType.A, 60, "1.1.1.1")), doReturn(recordResponse(List.of(RecordEntity.build("test.example.com", RecordType.A, 60, "1.1.1.1")),
new ResultInfo(1, 1, 2, 1, 2))) new ResultInfo(1, 1, 2, 1, 2)))
@@ -558,7 +558,7 @@ class CfDnsClientMockTest {
verify(spyClient).getRequest( verify(spyClient).getRequest(
eq("/zones/" + TEST_ZONE_ID + "/dns_records?name=example.com&order=name&direction=asc&page=1&per_page=" eq("/zones/" + TEST_ZONE_ID + "/dns_records?name=example.com&order=name&direction=asc&page=1&per_page="
+ CfDnsClient.MAX_RECORDS_PER_PAGE), + CfDnsClient.RECORDS_PER_PAGE),
eq(RecordMultipleResponse.class)); eq(RecordMultipleResponse.class));
} }
@@ -618,7 +618,7 @@ class CfDnsClientMockTest {
assertEquals(1, spyClient.recordList(createTestZone(), null).size()); assertEquals(1, spyClient.recordList(createTestZone(), null).size());
verify(spyClient).getRequest(eq("/zones/" + TEST_ZONE_ID verify(spyClient).getRequest(eq("/zones/" + TEST_ZONE_ID
+ "/dns_records?order=name&direction=asc&page=1&per_page=" + PagingRequest.MAX_PER_PAGE), + "/dns_records?order=name&direction=asc&page=1&per_page=" + CfDnsClient.RECORDS_PER_PAGE),
eq(RecordMultipleResponse.class)); eq(RecordMultipleResponse.class));
} }
@@ -628,7 +628,7 @@ class CfDnsClientMockTest {
doReturn(recordResponse(List.of(), new ResultInfo(0))) doReturn(recordResponse(List.of(), new ResultInfo(0)))
.when(spyClient).getRequest(anyString(), eq(RecordMultipleResponse.class)); .when(spyClient).getRequest(anyString(), eq(RecordMultipleResponse.class));
spyClient.recordList(createTestZone(), PagingRequest.of(2, 42)); spyClient.recordList(createTestZone(), PagingRequest.forRecords(2, 42));
verify(spyClient).getRequest(eq("/zones/" + TEST_ZONE_ID verify(spyClient).getRequest(eq("/zones/" + TEST_ZONE_ID
+ "/dns_records?order=name&direction=asc&page=2&per_page=42"), + "/dns_records?order=name&direction=asc&page=2&per_page=42"),
@@ -645,10 +645,10 @@ class CfDnsClientMockTest {
spyClient.recordListBySubdomain(createTestZone(), "www", RecordType.TXT); spyClient.recordListBySubdomain(createTestZone(), "www", RecordType.TXT);
verify(spyClient).getRequest(eq("/zones/" + TEST_ZONE_ID + "/dns_records?type=MX&order=name&direction=asc&page=1&per_page=" verify(spyClient).getRequest(eq("/zones/" + TEST_ZONE_ID + "/dns_records?type=MX&order=name&direction=asc&page=1&per_page="
+ CfDnsClient.MAX_RECORDS_PER_PAGE), eq(RecordMultipleResponse.class)); + CfDnsClient.RECORDS_PER_PAGE), eq(RecordMultipleResponse.class));
verify(spyClient).getRequest(eq("/zones/" + TEST_ZONE_ID verify(spyClient).getRequest(eq("/zones/" + TEST_ZONE_ID
+ "/dns_records?name=www.example.com&type=TXT&order=name&direction=asc&page=1&per_page=" + "/dns_records?name=www.example.com&type=TXT&order=name&direction=asc&page=1&per_page="
+ CfDnsClient.MAX_RECORDS_PER_PAGE), eq(RecordMultipleResponse.class)); + CfDnsClient.RECORDS_PER_PAGE), eq(RecordMultipleResponse.class));
} }
@Test @Test
@@ -669,7 +669,7 @@ class CfDnsClientMockTest {
assertEquals(List.of("A", "AAAA"), records.stream().map(RecordEntity::getType).toList()); assertEquals(List.of("A", "AAAA"), records.stream().map(RecordEntity::getType).toList());
verify(spyClient).getRequest(eq("/zones/" + TEST_ZONE_ID + "/dns_records?order=name&direction=asc&page=1&per_page=" verify(spyClient).getRequest(eq("/zones/" + TEST_ZONE_ID + "/dns_records?order=name&direction=asc&page=1&per_page="
+ CfDnsClient.MAX_RECORDS_PER_PAGE), eq(RecordMultipleResponse.class)); + CfDnsClient.RECORDS_PER_PAGE), eq(RecordMultipleResponse.class));
} }
private static RecordEntity fetchedMxRecord() { private static RecordEntity fetchedMxRecord() {
@@ -803,10 +803,10 @@ class CfDnsClientMockTest {
spyClient.recordListBySubdomain(createTestZone(), "0/26"); spyClient.recordListBySubdomain(createTestZone(), "0/26");
verify(spyClient).getRequest(eq("/zones/" + TEST_ZONE_ID verify(spyClient).getRequest(eq("/zones/" + TEST_ZONE_ID
+ "/dns_records?name=%24%28reboot%29.example.com&order=name&direction=asc&page=1&per_page=" + CfDnsClient.MAX_RECORDS_PER_PAGE), + "/dns_records?name=%24%28reboot%29.example.com&order=name&direction=asc&page=1&per_page=" + CfDnsClient.RECORDS_PER_PAGE),
eq(RecordMultipleResponse.class)); eq(RecordMultipleResponse.class));
verify(spyClient).getRequest(eq("/zones/" + TEST_ZONE_ID verify(spyClient).getRequest(eq("/zones/" + TEST_ZONE_ID
+ "/dns_records?name=0%2F26.example.com&order=name&direction=asc&page=1&per_page=" + CfDnsClient.MAX_RECORDS_PER_PAGE), + "/dns_records?name=0%2F26.example.com&order=name&direction=asc&page=1&per_page=" + CfDnsClient.RECORDS_PER_PAGE),
eq(RecordMultipleResponse.class)); eq(RecordMultipleResponse.class));
} }
@@ -832,7 +832,7 @@ class CfDnsClientMockTest {
private static String recordsPage(int page) { private static String recordsPage(int page) {
return "/zones/" + TEST_ZONE_ID + "/dns_records?order=name&direction=asc&page=" + page return "/zones/" + TEST_ZONE_ID + "/dns_records?order=name&direction=asc&page=" + page
+ "&per_page=" + PagingRequest.MAX_PER_PAGE; + "&per_page=" + CfDnsClient.RECORDS_PER_PAGE;
} }
@Test @Test
@@ -1,62 +1,80 @@
package codes.thischwa.cf.model; package codes.thischwa.cf.model;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
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 org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*; class PagingRequestTest {
public class PagingRequestTest { @Test
void testBuildPath() {
String result = PagingRequest.defaultPaging().addQueryString("/zones");
assertEquals("/zones?page=1&per_page=50", result);
}
@Test @Test
void testBuildPath() { void testBuildPathWithExistingQuery() {
String result = PagingRequest.defaultPaging().addQueryString("/zones"); String result = PagingRequest.forRecords(10, 100).addQueryString("/zones?foo=bar");
assertEquals("/zones?page=1&per_page=50", result); assertEquals("/zones?foo=bar&page=10&per_page=100", result);
} }
@Test @Test
void testPagingRequestBoundaries() { void testPagingRequestBoundaries() {
assertDoesNotThrow(() -> PagingRequest.of(1, 1)); assertDoesNotThrow(() -> PagingRequest.forRecords(1, 1));
assertDoesNotThrow(() -> PagingRequest.of(1, 5_000_000)); assertDoesNotThrow(() -> PagingRequest.forRecords(1, PagingRequest.MAX_RECORDS_PER_PAGE));
assertThrows(IllegalArgumentException.class, () -> PagingRequest.of(0, 1)); assertThrows(IllegalArgumentException.class, () -> PagingRequest.forRecords(0, 1));
assertThrows(IllegalArgumentException.class, () -> PagingRequest.of(1, 0)); assertThrows(IllegalArgumentException.class, () -> PagingRequest.forRecords(1, 0));
assertThrows(IllegalArgumentException.class, () -> PagingRequest.of(1, 5_000_001)); assertThrows(IllegalArgumentException.class,
} () -> PagingRequest.forRecords(1, PagingRequest.MAX_RECORDS_PER_PAGE + 1));
}
@Test @Test
void testSettersValidatePagingValues() { void testZonePageSizeBoundaries() {
PagingRequest request = PagingRequest.of(1, 50); assertDoesNotThrow(() -> PagingRequest.forZones(1, PagingRequest.MIN_ZONES_PER_PAGE));
assertDoesNotThrow(() -> PagingRequest.forZones(1, PagingRequest.MAX_ZONES_PER_PAGE));
assertThrows(IllegalArgumentException.class,
() -> PagingRequest.forZones(1, PagingRequest.MIN_ZONES_PER_PAGE - 1));
assertThrows(IllegalArgumentException.class,
() -> PagingRequest.forZones(1, PagingRequest.MAX_ZONES_PER_PAGE + 1));
}
assertThrows(IllegalArgumentException.class, () -> request.setPage(0)); @Test
assertThrows(IllegalArgumentException.class, () -> request.setPerPage(5_000_001)); void testNextAndWithPageReturnNewRequests() {
assertEquals(1, request.getPage()); PagingRequest request = PagingRequest.forRecords(2, 50);
assertEquals(50, request.getPerPage());
}
@Test assertEquals(PagingRequest.forRecords(3, 50), request.next());
void testBuildPathAdditional() { assertEquals(PagingRequest.forRecords(5, 50), request.withPage(5));
String result = new PagingRequest( 10, 100).addQueryString("/zones?foo=bar"); assertEquals(PagingRequest.forRecords(2, 50), request);
assertEquals("/zones?foo=bar&page=10&per_page=100", result); }
}
@Test @Test
void testGetPagingParams() { void testRecordMethods() {
PagingRequest request = PagingRequest.of(2, 50); PagingRequest first = PagingRequest.forRecords(1, 10);
java.util.Map<String, String> params = request.getPagingParams(); PagingRequest second = PagingRequest.forRecords(1, 10);
assertEquals("2", params.get("page"));
assertEquals("50", params.get("perPage"));
}
@Test assertEquals(first, second);
void testLombokMethods() { assertEquals(first.hashCode(), second.hashCode());
PagingRequest req1 = PagingRequest.of(1, 10); assertTrue(first.toString().contains("page=1"));
PagingRequest req2 = PagingRequest.of(1, 10); assertEquals(1, first.page());
assertEquals(req1, req2); assertEquals(10, first.perPage());
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());
}
@Test
void testValidationMessagesContainInvalidValues() {
IllegalArgumentException pageException = assertThrows(IllegalArgumentException.class,
() -> PagingRequest.forRecords(0, 10));
assertTrue(pageException.getMessage().contains("0"));
IllegalArgumentException perPageException = assertThrows(IllegalArgumentException.class,
() -> PagingRequest.forRecords(1, 0));
assertTrue(perPageException.getMessage().contains("0"));
}
@Test
void testAddQueryStringRejectsNullEndpoint() {
assertThrows(NullPointerException.class, () -> PagingRequest.defaultPaging().addQueryString(null));
}
} }