Fix line endings (#513)

* Adjust gitattributes file (mark some files binary, mark bat files as using crlf endings)
* Fix remaining line endings issues
This commit is contained in:
Daniel Chao
2024-06-04 07:55:33 -07:00
committed by GitHub
parent 207d0c78f0
commit c0a7080287
9 changed files with 569 additions and 562 deletions

7
.gitattributes vendored
View File

@@ -5,3 +5,10 @@
*.pkl linguist-language=Groovy *.pkl linguist-language=Groovy
* text eol=lf * text eol=lf
*.bat text eol=crlf
*.gif binary
*.jar binary
*.woff2 binary
*.pem binary
*.png binary

184
gradlew.bat vendored
View File

@@ -1,92 +1,92 @@
@rem @rem
@rem Copyright 2015 the original author or authors. @rem Copyright 2015 the original author or authors.
@rem @rem
@rem Licensed under the Apache License, Version 2.0 (the "License"); @rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License. @rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at @rem You may obtain a copy of the License at
@rem @rem
@rem https://www.apache.org/licenses/LICENSE-2.0 @rem https://www.apache.org/licenses/LICENSE-2.0
@rem @rem
@rem Unless required by applicable law or agreed to in writing, software @rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS, @rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and @rem See the License for the specific language governing permissions and
@rem limitations under the License. @rem limitations under the License.
@rem @rem
@if "%DEBUG%"=="" @echo off @if "%DEBUG%"=="" @echo off
@rem ########################################################################## @rem ##########################################################################
@rem @rem
@rem Gradle startup script for Windows @rem Gradle startup script for Windows
@rem @rem
@rem ########################################################################## @rem ##########################################################################
@rem Set local scope for the variables with windows NT shell @rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0 set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=. if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused @rem This is normally unused
set APP_BASE_NAME=%~n0 set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME% set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter. @rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe @rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1 %JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2 echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2 echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2 echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2 echo location of your Java installation. 1>&2
goto fail goto fail
:findJavaFromJavaHome :findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=% set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute if exist "%JAVA_EXE%" goto execute
echo. 1>&2 echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2 echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2 echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2 echo location of your Java installation. 1>&2
goto fail goto fail
:execute :execute
@rem Setup the command line @rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle @rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end :end
@rem End local scope for the variables with windows NT shell @rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd if %ERRORLEVEL% equ 0 goto mainEnd
:fail :fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code! rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL% set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1 if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE% exit /b %EXIT_CODE%
:mainEnd :mainEnd
if "%OS%"=="Windows_NT" endlocal if "%OS%"=="Windows_NT" endlocal
:omega :omega

View File

@@ -1,19 +1,19 @@
plugins { plugins {
pklAllProjects pklAllProjects
pklJavaLibrary pklJavaLibrary
pklPublishLibrary pklPublishLibrary
} }
publishing { publishing {
publications { publications {
named<MavenPublication>("library") { named<MavenPublication>("library") {
pom { pom {
url.set("https://github.com/apple/pkl/tree/main/pkl-certs") url.set("https://github.com/apple/pkl/tree/main/pkl-certs")
description.set(""" description.set("""
Pkl's built-in CA certificates. Pkl's built-in CA certificates.
Used by Pkl CLIs and optionally supported by pkl-core.") Used by Pkl CLIs and optionally supported by pkl-core.")
""".trimIndent()) """.trimIndent())
} }
} }
} }
} }

View File

@@ -1,34 +1,34 @@
package org.pkl.core.http package org.pkl.core.http
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertDoesNotThrow import org.junit.jupiter.api.assertDoesNotThrow
import org.junit.jupiter.api.assertThrows import org.junit.jupiter.api.assertThrows
import java.net.URI import java.net.URI
import java.net.http.HttpRequest import java.net.http.HttpRequest
import java.net.http.HttpResponse import java.net.http.HttpResponse
class DummyHttpClientTest { class DummyHttpClientTest {
@Test @Test
fun `refuses to send messages`() { fun `refuses to send messages`() {
val client = HttpClient.dummyClient() val client = HttpClient.dummyClient()
val request = HttpRequest.newBuilder(URI("https://example.com")).build() val request = HttpRequest.newBuilder(URI("https://example.com")).build()
assertThrows<AssertionError> { assertThrows<AssertionError> {
client.send(request, HttpResponse.BodyHandlers.discarding()) client.send(request, HttpResponse.BodyHandlers.discarding())
} }
assertThrows<AssertionError> { assertThrows<AssertionError> {
client.send(request, HttpResponse.BodyHandlers.discarding()) client.send(request, HttpResponse.BodyHandlers.discarding())
} }
} }
@Test @Test
fun `can be closed`() { fun `can be closed`() {
val client = HttpClient.dummyClient() val client = HttpClient.dummyClient()
assertDoesNotThrow { assertDoesNotThrow {
client.close() client.close()
client.close() client.close()
} }
} }
} }

View File

@@ -1,149 +1,149 @@
package org.pkl.core.http package org.pkl.core.http
import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertDoesNotThrow import org.junit.jupiter.api.assertDoesNotThrow
import org.junit.jupiter.api.assertThrows import org.junit.jupiter.api.assertThrows
import org.junit.jupiter.api.io.TempDir import org.junit.jupiter.api.io.TempDir
import org.pkl.commons.test.FileTestUtils import org.pkl.commons.test.FileTestUtils
import org.pkl.core.Release import org.pkl.core.Release
import java.net.URI import java.net.URI
import java.net.http.HttpRequest import java.net.http.HttpRequest
import java.net.http.HttpResponse import java.net.http.HttpResponse
import java.nio.file.Path import java.nio.file.Path
import java.time.Duration import java.time.Duration
import kotlin.io.path.copyTo import kotlin.io.path.copyTo
import kotlin.io.path.createDirectories import kotlin.io.path.createDirectories
import kotlin.io.path.createFile import kotlin.io.path.createFile
class HttpClientTest { class HttpClientTest {
@Test @Test
fun `can build default client`() { fun `can build default client`() {
val client = assertDoesNotThrow { val client = assertDoesNotThrow {
HttpClient.builder().build() HttpClient.builder().build()
} }
assertThat(client).isInstanceOf(RequestRewritingClient::class.java) assertThat(client).isInstanceOf(RequestRewritingClient::class.java)
client as RequestRewritingClient client as RequestRewritingClient
val release = Release.current() val release = Release.current()
assertThat(client.userAgent).isEqualTo("Pkl/${release.version()} (${release.os()}; ${release.flavor()})") assertThat(client.userAgent).isEqualTo("Pkl/${release.version()} (${release.os()}; ${release.flavor()})")
assertThat(client.requestTimeout).isEqualTo(Duration.ofSeconds(60)) assertThat(client.requestTimeout).isEqualTo(Duration.ofSeconds(60))
assertThat(client.delegate).isInstanceOf(JdkHttpClient::class.java) assertThat(client.delegate).isInstanceOf(JdkHttpClient::class.java)
val delegate = client.delegate as JdkHttpClient val delegate = client.delegate as JdkHttpClient
assertThat(delegate.underlying.connectTimeout()).hasValue(Duration.ofSeconds(60)) assertThat(delegate.underlying.connectTimeout()).hasValue(Duration.ofSeconds(60))
} }
@Test @Test
fun `can build custom client`() { fun `can build custom client`() {
val client = HttpClient.builder() val client = HttpClient.builder()
.setUserAgent("Agent 1") .setUserAgent("Agent 1")
.setRequestTimeout(Duration.ofHours(86)) .setRequestTimeout(Duration.ofHours(86))
.setConnectTimeout(Duration.ofMinutes(42)) .setConnectTimeout(Duration.ofMinutes(42))
.build() as RequestRewritingClient .build() as RequestRewritingClient
assertThat(client.userAgent).isEqualTo("Agent 1") assertThat(client.userAgent).isEqualTo("Agent 1")
assertThat(client.requestTimeout).isEqualTo(Duration.ofHours(86)) assertThat(client.requestTimeout).isEqualTo(Duration.ofHours(86))
val delegate = client.delegate as JdkHttpClient val delegate = client.delegate as JdkHttpClient
assertThat(delegate.underlying.connectTimeout()).hasValue(Duration.ofMinutes(42)) assertThat(delegate.underlying.connectTimeout()).hasValue(Duration.ofMinutes(42))
} }
@Test @Test
fun `can load certificates from file system`() { fun `can load certificates from file system`() {
assertDoesNotThrow { assertDoesNotThrow {
HttpClient.builder().addCertificates(FileTestUtils.selfSignedCertificate).build() HttpClient.builder().addCertificates(FileTestUtils.selfSignedCertificate).build()
} }
} }
@Test @Test
fun `certificate file located on file system cannot be empty`(@TempDir tempDir: Path) { fun `certificate file located on file system cannot be empty`(@TempDir tempDir: Path) {
val file = tempDir.resolve("certs.pem").createFile() val file = tempDir.resolve("certs.pem").createFile()
val e = assertThrows<HttpClientInitException> { val e = assertThrows<HttpClientInitException> {
HttpClient.builder().addCertificates(file).build() HttpClient.builder().addCertificates(file).build()
} }
assertThat(e).hasMessageContaining("empty") assertThat(e).hasMessageContaining("empty")
} }
@Test @Test
fun `can load certificates from class path`() { fun `can load certificates from class path`() {
assertDoesNotThrow { assertDoesNotThrow {
HttpClient.builder().addCertificates(javaClass.getResource("/org/pkl/certs/PklCARoots.pem")!!.toURI()).build() HttpClient.builder().addCertificates(javaClass.getResource("/org/pkl/certs/PklCARoots.pem")!!.toURI()).build()
} }
} }
@Test @Test
fun `only allows loading jar and file certificate URIs`() { fun `only allows loading jar and file certificate URIs`() {
assertThrows<HttpClientInitException> { assertThrows<HttpClientInitException> {
HttpClient.builder().addCertificates(URI("https://example.com")) HttpClient.builder().addCertificates(URI("https://example.com"))
} }
} }
@Test @Test
fun `certificate file located on class path cannot be empty`() { fun `certificate file located on class path cannot be empty`() {
val uri = javaClass.getResource("emptyCerts.pem")!!.toURI() val uri = javaClass.getResource("emptyCerts.pem")!!.toURI()
val e = assertThrows<HttpClientInitException> { val e = assertThrows<HttpClientInitException> {
HttpClient.builder().addCertificates(uri).build() HttpClient.builder().addCertificates(uri).build()
} }
assertThat(e).hasMessageContaining("empty") assertThat(e).hasMessageContaining("empty")
} }
@Test @Test
fun `can load built-in certificates`() { fun `can load built-in certificates`() {
assertDoesNotThrow { assertDoesNotThrow {
HttpClient.builder().addBuiltInCertificates().build() HttpClient.builder().addBuiltInCertificates().build()
} }
} }
@Test @Test
fun `can load certificates from Pkl user home cacerts directory`(@TempDir tempDir: Path) { fun `can load certificates from Pkl user home cacerts directory`(@TempDir tempDir: Path) {
val certsDir = tempDir.resolve(".pkl") val certsDir = tempDir.resolve(".pkl")
.resolve("cacerts") .resolve("cacerts")
.createDirectories() .createDirectories()
.also { dir -> .also { dir ->
FileTestUtils.selfSignedCertificate.copyTo(dir.resolve("certs.pem")) FileTestUtils.selfSignedCertificate.copyTo(dir.resolve("certs.pem"))
} }
assertDoesNotThrow { assertDoesNotThrow {
HttpClientBuilder(certsDir).addDefaultCliCertificates().build() HttpClientBuilder(certsDir).addDefaultCliCertificates().build()
} }
} }
@Test @Test
fun `loading certificates from cacerts directory falls back to built-in certificates`(@TempDir certsDir: Path) { fun `loading certificates from cacerts directory falls back to built-in certificates`(@TempDir certsDir: Path) {
assertDoesNotThrow { assertDoesNotThrow {
HttpClientBuilder(certsDir).addDefaultCliCertificates().build() HttpClientBuilder(certsDir).addDefaultCliCertificates().build()
} }
} }
@Test @Test
fun `can be closed multiple times`() { fun `can be closed multiple times`() {
val client = HttpClient.builder().build() val client = HttpClient.builder().build()
assertDoesNotThrow { assertDoesNotThrow {
client.close() client.close()
client.close() client.close()
} }
} }
@Test @Test
fun `refuses to send messages once closed`() { fun `refuses to send messages once closed`() {
val client = HttpClient.builder().build() val client = HttpClient.builder().build()
val request = HttpRequest.newBuilder(URI("https://example.com")).build() val request = HttpRequest.newBuilder(URI("https://example.com")).build()
client.close() client.close()
assertThrows<IllegalStateException> { assertThrows<IllegalStateException> {
client.send(request, HttpResponse.BodyHandlers.discarding()) client.send(request, HttpResponse.BodyHandlers.discarding())
} }
assertThrows<IllegalStateException> { assertThrows<IllegalStateException> {
client.send(request, HttpResponse.BodyHandlers.discarding()) client.send(request, HttpResponse.BodyHandlers.discarding())
} }
} }
} }

View File

@@ -1,34 +1,34 @@
package org.pkl.core.http package org.pkl.core.http
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertDoesNotThrow import org.junit.jupiter.api.assertDoesNotThrow
import org.junit.jupiter.api.assertThrows import org.junit.jupiter.api.assertThrows
import java.net.URI import java.net.URI
import java.net.http.HttpRequest import java.net.http.HttpRequest
import java.net.http.HttpResponse.BodyHandlers import java.net.http.HttpResponse.BodyHandlers
class LazyHttpClientTest { class LazyHttpClientTest {
@Test @Test
fun `builds underlying client on first send`() { fun `builds underlying client on first send`() {
val client = HttpClient.builder() val client = HttpClient.builder()
.addCertificates(javaClass.getResource("brokenCerts.pem")!!.toURI()) .addCertificates(javaClass.getResource("brokenCerts.pem")!!.toURI())
.buildLazily() .buildLazily()
val request = HttpRequest.newBuilder(URI("https://example.com")).build() val request = HttpRequest.newBuilder(URI("https://example.com")).build()
assertThrows<HttpClientInitException> { assertThrows<HttpClientInitException> {
client.send(request, BodyHandlers.discarding()) client.send(request, BodyHandlers.discarding())
} }
} }
@Test @Test
fun `does not build underlying client unnecessarily`() { fun `does not build underlying client unnecessarily`() {
val client = HttpClient.builder() val client = HttpClient.builder()
.addCertificates(javaClass.getResource("brokenCerts.pem")!!.toURI()) .addCertificates(javaClass.getResource("brokenCerts.pem")!!.toURI())
.buildLazily() .buildLazily()
assertDoesNotThrow { assertDoesNotThrow {
client.close() client.close()
client.close() client.close()
} }
} }
} }

View File

@@ -1,127 +1,127 @@
package org.pkl.core.http package org.pkl.core.http
import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatList import org.assertj.core.api.Assertions.assertThatList
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
import java.net.URI import java.net.URI
import java.net.http.HttpRequest import java.net.http.HttpRequest
import java.net.http.HttpRequest.BodyPublishers import java.net.http.HttpRequest.BodyPublishers
import java.net.http.HttpResponse.BodyHandlers import java.net.http.HttpResponse.BodyHandlers
import java.time.Duration import java.time.Duration
import java.net.http.HttpClient as JdkHttpClient import java.net.http.HttpClient as JdkHttpClient
class RequestRewritingClientTest { class RequestRewritingClientTest {
private val captured = RequestCapturingClient() private val captured = RequestCapturingClient()
private val client = RequestRewritingClient("Pkl", Duration.ofSeconds(42), -1, captured) private val client = RequestRewritingClient("Pkl", Duration.ofSeconds(42), -1, captured)
private val exampleUri = URI("https://example.com/foo/bar.html") private val exampleUri = URI("https://example.com/foo/bar.html")
private val exampleRequest = HttpRequest.newBuilder(exampleUri).build() private val exampleRequest = HttpRequest.newBuilder(exampleUri).build()
@Test @Test
fun `fills in missing User-Agent header`() { fun `fills in missing User-Agent header`() {
client.send(exampleRequest, BodyHandlers.discarding()) client.send(exampleRequest, BodyHandlers.discarding())
assertThatList(captured.request.headers().allValues("User-Agent")).containsOnly("Pkl") assertThatList(captured.request.headers().allValues("User-Agent")).containsOnly("Pkl")
} }
@Test @Test
fun `overrides existing User-Agent headers`() { fun `overrides existing User-Agent headers`() {
val request = HttpRequest.newBuilder(exampleUri) val request = HttpRequest.newBuilder(exampleUri)
.header("User-Agent", "Agent 1") .header("User-Agent", "Agent 1")
.header("User-Agent", "Agent 2") .header("User-Agent", "Agent 2")
.build() .build()
client.send(request, BodyHandlers.discarding()) client.send(request, BodyHandlers.discarding())
assertThatList(captured.request.headers().allValues("User-Agent")).containsOnly("Pkl") assertThatList(captured.request.headers().allValues("User-Agent")).containsOnly("Pkl")
} }
@Test @Test
fun `fills in missing request timeout`() { fun `fills in missing request timeout`() {
client.send(exampleRequest, BodyHandlers.discarding()) client.send(exampleRequest, BodyHandlers.discarding())
assertThat(captured.request.timeout()).hasValue(Duration.ofSeconds(42)) assertThat(captured.request.timeout()).hasValue(Duration.ofSeconds(42))
} }
@Test @Test
fun `leaves existing request timeout intact`() { fun `leaves existing request timeout intact`() {
val request = HttpRequest.newBuilder(exampleUri) val request = HttpRequest.newBuilder(exampleUri)
.timeout(Duration.ofMinutes(33)) .timeout(Duration.ofMinutes(33))
.build() .build()
client.send(request, BodyHandlers.discarding()) client.send(request, BodyHandlers.discarding())
assertThat(captured.request.timeout()).hasValue(Duration.ofMinutes(33)) assertThat(captured.request.timeout()).hasValue(Duration.ofMinutes(33))
} }
@Test @Test
fun `fills in missing HTTP version`() { fun `fills in missing HTTP version`() {
client.send(exampleRequest, BodyHandlers.discarding()) client.send(exampleRequest, BodyHandlers.discarding())
assertThat(captured.request.version()).hasValue(JdkHttpClient.Version.HTTP_2) assertThat(captured.request.version()).hasValue(JdkHttpClient.Version.HTTP_2)
} }
@Test @Test
fun `leaves existing HTTP version intact`() { fun `leaves existing HTTP version intact`() {
val request = HttpRequest.newBuilder(exampleUri) val request = HttpRequest.newBuilder(exampleUri)
.version(JdkHttpClient.Version.HTTP_1_1) .version(JdkHttpClient.Version.HTTP_1_1)
.build() .build()
client.send(request, BodyHandlers.discarding()) client.send(request, BodyHandlers.discarding())
assertThat(captured.request.version()).hasValue(JdkHttpClient.Version.HTTP_1_1) assertThat(captured.request.version()).hasValue(JdkHttpClient.Version.HTTP_1_1)
} }
@Test @Test
fun `leaves default method intact`() { fun `leaves default method intact`() {
val request = HttpRequest.newBuilder(exampleUri).build() val request = HttpRequest.newBuilder(exampleUri).build()
client.send(request, BodyHandlers.discarding()) client.send(request, BodyHandlers.discarding())
assertThat(captured.request.method()).isEqualTo("GET") assertThat(captured.request.method()).isEqualTo("GET")
} }
@Test @Test
fun `leaves explicit method intact`() { fun `leaves explicit method intact`() {
val request = HttpRequest.newBuilder(exampleUri) val request = HttpRequest.newBuilder(exampleUri)
.DELETE() .DELETE()
.build() .build()
client.send(request, BodyHandlers.discarding()) client.send(request, BodyHandlers.discarding())
assertThat(captured.request.method()).isEqualTo("DELETE") assertThat(captured.request.method()).isEqualTo("DELETE")
} }
@Test @Test
fun `leaves body publisher intact`() { fun `leaves body publisher intact`() {
val publisher = BodyPublishers.ofString("body") val publisher = BodyPublishers.ofString("body")
val request = HttpRequest.newBuilder(exampleUri) val request = HttpRequest.newBuilder(exampleUri)
.PUT(publisher) .PUT(publisher)
.build() .build()
client.send(request, BodyHandlers.discarding()) client.send(request, BodyHandlers.discarding())
assertThat(captured.request.bodyPublisher().get()).isSameAs(publisher) assertThat(captured.request.bodyPublisher().get()).isSameAs(publisher)
} }
@Test @Test
fun `rewrites port 0 if test port is set`() { fun `rewrites port 0 if test port is set`() {
val captured = RequestCapturingClient() val captured = RequestCapturingClient()
val client = RequestRewritingClient("Pkl", Duration.ofSeconds(42), 5000, captured) val client = RequestRewritingClient("Pkl", Duration.ofSeconds(42), 5000, captured)
val request = HttpRequest.newBuilder(URI("https://example.com:0")).build() val request = HttpRequest.newBuilder(URI("https://example.com:0")).build()
client.send(request, BodyHandlers.discarding()) client.send(request, BodyHandlers.discarding())
assertThat(captured.request.uri().port).isEqualTo(5000) assertThat(captured.request.uri().port).isEqualTo(5000)
} }
@Test @Test
fun `leaves port 0 intact if no test port is set`() { fun `leaves port 0 intact if no test port is set`() {
val request = HttpRequest.newBuilder(URI("https://example.com:0")).build() val request = HttpRequest.newBuilder(URI("https://example.com:0")).build()
client.send(request, BodyHandlers.discarding()) client.send(request, BodyHandlers.discarding())
assertThat(captured.request.uri().port).isEqualTo(0) assertThat(captured.request.uri().port).isEqualTo(0)
} }
} }

View File

@@ -1,48 +1,48 @@
package org.pkl.core.util package org.pkl.core.util
import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
import java.io.IOException import java.io.IOException
import java.lang.Error import java.lang.Error
class ExceptionsTest { class ExceptionsTest {
@Test @Test
fun `get root cause of simple exception`() { fun `get root cause of simple exception`() {
val e = IOException("io") val e = IOException("io")
assertThat(Exceptions.getRootCause(e)).isSameAs(e) assertThat(Exceptions.getRootCause(e)).isSameAs(e)
} }
@Test @Test
fun `get root cause of nested exception`() { fun `get root cause of nested exception`() {
val e = IOException("io") val e = IOException("io")
val e2 = RuntimeException("runtime") val e2 = RuntimeException("runtime")
val e3 = Error("error") val e3 = Error("error")
e.initCause(e2) e.initCause(e2)
e2.initCause(e3) e2.initCause(e3)
assertThat(Exceptions.getRootCause(e)).isSameAs(e3) assertThat(Exceptions.getRootCause(e)).isSameAs(e3)
} }
@Test @Test
fun `get root reason`() { fun `get root reason`() {
val e = IOException("io") val e = IOException("io")
val e2 = RuntimeException("the root reason") val e2 = RuntimeException("the root reason")
e.initCause(e2) e.initCause(e2)
assertThat(Exceptions.getRootReason(e)).isEqualTo("the root reason") assertThat(Exceptions.getRootReason(e)).isEqualTo("the root reason")
} }
@Test @Test
fun `get root reason if null`() { fun `get root reason if null`() {
val e = IOException("io") val e = IOException("io")
val e2 = RuntimeException(null as String?) val e2 = RuntimeException(null as String?)
e.initCause(e2) e.initCause(e2)
assertThat(Exceptions.getRootReason(e)).isEqualTo("(unknown reason)") assertThat(Exceptions.getRootReason(e)).isEqualTo("(unknown reason)")
} }
@Test @Test
fun `get root reason if empty`() { fun `get root reason if empty`() {
val e = IOException("io") val e = IOException("io")
val e2 = RuntimeException("") val e2 = RuntimeException("")
e.initCause(e2) e.initCause(e2)
assertThat(Exceptions.getRootReason(e)).isEqualTo("(unknown reason)") assertThat(Exceptions.getRootReason(e)).isEqualTo("(unknown reason)")
} }
} }

View File

@@ -1,59 +1,59 @@
package org.pkl.core.util package org.pkl.core.util
import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertDoesNotThrow import org.junit.jupiter.api.assertDoesNotThrow
import org.junit.jupiter.api.assertThrows import org.junit.jupiter.api.assertThrows
import org.pkl.commons.test.FakeHttpResponse import org.pkl.commons.test.FakeHttpResponse
import java.io.IOException import java.io.IOException
import java.net.URI import java.net.URI
class HttpUtilsTest { class HttpUtilsTest {
@Test @Test
fun isHttpUrl() { fun isHttpUrl() {
assertThat(HttpUtils.isHttpUrl(URI("http://example.com"))).isTrue assertThat(HttpUtils.isHttpUrl(URI("http://example.com"))).isTrue
assertThat(HttpUtils.isHttpUrl(URI("https://example.com"))).isTrue assertThat(HttpUtils.isHttpUrl(URI("https://example.com"))).isTrue
assertThat(HttpUtils.isHttpUrl(URI("HtTpS://example.com"))).isTrue assertThat(HttpUtils.isHttpUrl(URI("HtTpS://example.com"))).isTrue
assertThat(HttpUtils.isHttpUrl(URI("file://example.com"))).isFalse assertThat(HttpUtils.isHttpUrl(URI("file://example.com"))).isFalse
assertThat(HttpUtils.isHttpUrl(URI("http://example.com").toURL())).isTrue assertThat(HttpUtils.isHttpUrl(URI("http://example.com").toURL())).isTrue
assertThat(HttpUtils.isHttpUrl(URI("https://example.com").toURL())).isTrue assertThat(HttpUtils.isHttpUrl(URI("https://example.com").toURL())).isTrue
assertThat(HttpUtils.isHttpUrl(URI("HtTpS://example.com").toURL())).isTrue assertThat(HttpUtils.isHttpUrl(URI("HtTpS://example.com").toURL())).isTrue
assertThat(HttpUtils.isHttpUrl(URI("file://example.com").toURL())).isFalse assertThat(HttpUtils.isHttpUrl(URI("file://example.com").toURL())).isFalse
} }
@Test @Test
fun checkHasStatusCode200() { fun checkHasStatusCode200() {
val response = FakeHttpResponse.withoutBody { val response = FakeHttpResponse.withoutBody {
statusCode = 200 statusCode = 200
} }
assertDoesNotThrow { assertDoesNotThrow {
HttpUtils.checkHasStatusCode200(response) HttpUtils.checkHasStatusCode200(response)
} }
val response2 = FakeHttpResponse.withoutBody { val response2 = FakeHttpResponse.withoutBody {
statusCode = 404 statusCode = 404
} }
assertThrows<IOException> { assertThrows<IOException> {
HttpUtils.checkHasStatusCode200(response2) HttpUtils.checkHasStatusCode200(response2)
} }
} }
@Test @Test
fun setPort() { fun setPort() {
assertThrows<IllegalArgumentException> { assertThrows<IllegalArgumentException> {
HttpUtils.setPort(URI("https://example.com"), -1) HttpUtils.setPort(URI("https://example.com"), -1)
} }
assertThrows<IllegalArgumentException> { assertThrows<IllegalArgumentException> {
HttpUtils.setPort(URI("https://example.com"), 65536) HttpUtils.setPort(URI("https://example.com"), 65536)
} }
assertThat(HttpUtils.setPort(URI("http://example.com"), 123)) assertThat(HttpUtils.setPort(URI("http://example.com"), 123))
.isEqualTo(URI("http://example.com:123")) .isEqualTo(URI("http://example.com:123"))
assertThat(HttpUtils.setPort(URI("http://example.com:456"), 123)) assertThat(HttpUtils.setPort(URI("http://example.com:456"), 123))
.isEqualTo(URI("http://example.com:123")) .isEqualTo(URI("http://example.com:123"))
assertThat(HttpUtils.setPort(URI("https://example.com/foo/bar.baz?query=1#fragment"), 123)) assertThat(HttpUtils.setPort(URI("https://example.com/foo/bar.baz?query=1#fragment"), 123))
.isEqualTo(URI("https://example.com:123/foo/bar.baz?query=1#fragment")) .isEqualTo(URI("https://example.com:123/foo/bar.baz?query=1#fragment"))
assertThat(HttpUtils.setPort(URI("https://example.com:456/foo/bar.baz?query=1#fragment"), 123)) assertThat(HttpUtils.setPort(URI("https://example.com:456/foo/bar.baz?query=1#fragment"), 123))
.isEqualTo(URI("https://example.com:123/foo/bar.baz?query=1#fragment")) .isEqualTo(URI("https://example.com:123/foo/bar.baz?query=1#fragment"))
} }
} }