Skip to content

Commit 162af93

Browse files
authored
make api rate limit test more robust (#6984)
* make api rate limit test a little more robust * Update condition for time exeeded
1 parent fc5bd85 commit 162af93

File tree

2 files changed

+31
-4
lines changed

2 files changed

+31
-4
lines changed

plugins/api/rate-limit/src/main/java/org/apache/cloudstack/ratelimit/ApiRateLimitServiceImpl.java

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,23 @@ public void setTimeToLive(int timeToLive) {
230230
this.timeToLive = timeToLive;
231231
}
232232

233+
protected int getTimeToLive() {
234+
return this.timeToLive;
235+
}
236+
237+
protected int getMaxAllowed() {
238+
return this.maxAllowed;
239+
}
240+
241+
protected int getIssued(Long accountId) {
242+
int ammount = 0;
243+
StoreEntry entry = _store.get(accountId);
244+
if (entry != null) {
245+
ammount = entry.getCounter();
246+
}
247+
return ammount;
248+
}
249+
233250
@Override
234251
public void setMaxAllowed(int max) {
235252
maxAllowed = max;

plugins/api/rate-limit/src/test/java/org/apache/cloudstack/ratelimit/ApiRateLimitTest.java

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -112,15 +112,25 @@ public void sequentialApiAccess() {
112112
public void canDoReasonableNumberOfApiAccessPerSecond() throws Exception {
113113
int allowedRequests = 200;
114114
s_limitService.setMaxAllowed(allowedRequests);
115-
s_limitService.setTimeToLive(1);
115+
s_limitService.setTimeToLive(5);
116+
long startTime = System.nanoTime();
116117

117118
User key = createFakeUser();
118119

119120
for (int i = 0; i < allowedRequests; i++) {
120-
assertTrue("We should allow " + allowedRequests + " requests per second, but failed at request " + i, isUnderLimit(key));
121+
assertTrue(String.format("We should allow %d requests per second, but failed at request %d.", allowedRequests, i), isUnderLimit(key));
121122
}
122-
123-
assertFalse("We should block >" + allowedRequests + " requests per second", isUnderLimit(key));
123+
// we cannot really say more about this test
124+
boolean underLimit = isUnderLimit(key);
125+
long endTime = System.nanoTime();
126+
System.out.println("time elapsed " + (endTime - startTime)/1000/1000 + " ms");
127+
int issued = s_limitService.getIssued(key.getAccountId());
128+
int timeToLive = s_limitService.getTimeToLive();
129+
130+
// this assertion is really invalid as we don´t know if we exceeded the time to live for the amount of api calls (for sure)
131+
// so only fail if timeToLive is not exeeded and we didn´t get the requested number of calls
132+
assertFalse(String.format("We should block >%d requests per %d seconds (managed %d, time elapsed %d ns)",
133+
s_limitService.getMaxAllowed(), timeToLive, issued, endTime - startTime), ((endTime - startTime)/1000000000 < timeToLive) && underLimit);
124134
}
125135

126136
@Test

0 commit comments

Comments
 (0)