Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active May 27, 2023 06:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dacr/5149a16dedf6d235c47cd03485c5b75b to your computer and use it in GitHub Desktop.
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/ee9d9e67135d037d22e463e922773d25bfdf1fc5
// 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.3.0"
//> 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