Last active
May 25, 2024 10:19
-
-
Save dacr/5149a16dedf6d235c47cd03485c5b75b to your computer and use it in GitHub Desktop.
Testing if a remote http server is reachable. / published by https://github.com/dacr/code-examples-manager #38906815-7ba7-43be-9c46-bded28296193/c1283b93b21af843b4e007e5474200c5cb6cfdb7
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// summary : Testing if a remote http server is reachable. | |
// keywords : scala, scalatest, netio, async | |
// publish : gist | |
// authors : David Crosson | |
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2) | |
// id : 38906815-7ba7-43be-9c46-bded28296193 | |
// created-on : 2019-06-05T20:46:10Z | |
// managed-by : https://github.com/dacr/code-examples-manager | |
// run-with : scala-cli $file | |
// --------------------- | |
//> using scala "3.4.2" | |
//> using dep "org.scalatest::scalatest:3.2.16" | |
//> using objectWrapper | |
// --------------------- | |
import org.scalatest.*, matchers.* | |
import scala.concurrent.* | |
// TODO requires more tests | |
// TODO refactor to async approach | |
def checkRemoteURL(url:String):Future[Boolean] = { | |
import ExecutionContext.Implicits.global | |
Future { new java.net.URL(url).openConnection() } | |
.map { cnx => | |
cnx.setConnectTimeout(5000) | |
cnx.setReadTimeout(5000) | |
cnx.setUseCaches(false) | |
cnx.setAllowUserInteraction(false) | |
cnx.connect() | |
cnx } | |
.map { _.getInputStream } | |
.map { scala.io.Source.fromInputStream(_) } | |
.map { in => in.close()} | |
.collect { case x => true } | |
.recover { case _ => false } | |
} | |
class RemoteURLTest extends flatspec.AsyncFlatSpec with should.Matchers { | |
override def suiteName: String = "RemoteURLTest" | |
"checkRemoteURL" should "return true with valid URL" ignore { | |
checkRemoteURL("http://httpbin.org").map { result => | |
result shouldBe true | |
} | |
} | |
it should "return false with invalid URL" ignore { | |
checkRemoteURL("http://httpbinxx.orgzz").map {result => | |
result shouldBe false | |
} | |
} | |
} | |
org.scalatest.tools.Runner.main(Array("-oDF", "-s", classOf[RemoteURLTest].getName)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment