3 * Copyright (C) 2009-2024 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.server.telemetry;
22 import java.io.IOException;
23 import java.util.Objects;
24 import okhttp3.MediaType;
25 import okhttp3.OkHttpClient;
26 import okhttp3.mockwebserver.MockResponse;
27 import okhttp3.mockwebserver.MockWebServer;
28 import okhttp3.mockwebserver.RecordedRequest;
29 import okio.GzipSource;
31 import org.assertj.core.api.Assertions;
32 import org.junit.Test;
33 import org.sonar.api.config.internal.MapSettings;
35 import static org.assertj.core.api.Assertions.assertThat;
36 import static org.sonar.process.ProcessProperties.Property.SONAR_TELEMETRY_URL;
38 public class TelemetryClientCompressionTest {
40 private final OkHttpClient okHttpClient = new OkHttpClient();
41 private final MockWebServer telemetryServer = new MockWebServer();
44 public void payload_is_gzip_encoded() throws IOException, InterruptedException {
45 telemetryServer.enqueue(new MockResponse().setResponseCode(200));
46 MapSettings settings = new MapSettings();
47 settings.setProperty(SONAR_TELEMETRY_URL.getKey(), telemetryServer.url("/").toString());
48 TelemetryClient underTest = new TelemetryClient(okHttpClient, settings.asConfig());
50 underTest.upload("payload compressed with gzip");
52 RecordedRequest request = telemetryServer.takeRequest();
54 String contentType = Objects.requireNonNull(request.getHeader("content-type"));
55 assertThat(MediaType.parse(contentType)).isEqualTo(MediaType.parse("application/json; charset=utf-8"));
56 assertThat(request.getHeader("content-encoding")).isEqualTo("gzip");
58 GzipSource source = new GzipSource(request.getBody());
59 String body = Okio.buffer(source).readUtf8();
60 Assertions.assertThat(body).isEqualTo("payload compressed with gzip");