3 * Copyright (C) 2009-2023 SonarSource SA
4 * mailto:info AT sonarsource DOT com
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 3 of the License, or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with this program; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 package org.sonar.alm.client.github;
22 import com.tngtech.java.junit.dataprovider.DataProvider;
23 import com.tngtech.java.junit.dataprovider.DataProviderRunner;
24 import com.tngtech.java.junit.dataprovider.UseDataProvider;
25 import org.junit.Rule;
26 import org.junit.Test;
27 import org.junit.runner.RunWith;
28 import org.slf4j.event.Level;
29 import org.sonar.api.testfixtures.log.LogTester;
31 import static java.lang.String.format;
32 import static org.assertj.core.api.Assertions.assertThat;
33 import static org.mockito.Mockito.mock;
34 import static org.mockito.Mockito.when;
35 import static org.sonar.alm.client.github.RatioBasedRateLimitChecker.RATE_RATIO_EXCEEDED_MESSAGE;
37 @RunWith(DataProviderRunner.class)
38 public class RatioBasedRateLimitCheckerTest {
41 public LogTester logTester = new LogTester();
42 private static final long MILLIS_BEFORE_RESET = 100L;
43 RatioBasedRateLimitChecker ratioBasedRateLimitChecker = new RatioBasedRateLimitChecker();
46 public static Object[][] rates() {
47 return new Object[][] {
48 {10000, 100000, false},
49 {10000, 10000, false},
60 @UseDataProvider("rates")
61 public void checkRateLimit(int limit, int remaining, boolean rateLimitShouldBeExceeded) throws InterruptedException {
62 ApplicationHttpClient.RateLimit record = mock();
63 when(record.limit()).thenReturn(limit);
64 when(record.remaining()).thenReturn(remaining);
65 when(record.reset()).thenReturn(System.currentTimeMillis() / 1000 + 1);
67 long start = System.currentTimeMillis();
68 boolean result = ratioBasedRateLimitChecker.checkRateLimit(record);
69 long stop = System.currentTimeMillis();
70 long totalTime = stop - start;
72 if (rateLimitShouldBeExceeded) {
73 assertThat(result).isTrue();
74 assertThat(stop).isGreaterThanOrEqualTo(record.reset());
75 assertThat(logTester.logs(Level.WARN)).contains(
76 format(RATE_RATIO_EXCEEDED_MESSAGE.replaceAll("\\{\\}", "%s"), limit - remaining, limit));
78 assertThat(result).isFalse();
79 assertThat(totalTime).isLessThan(MILLIS_BEFORE_RESET);
80 assertThat(logTester.logs(Level.WARN)).isEmpty();