Test cases for file upload using akka-http in Scala


Hello folks,

In my previous blog, i explained how to upload a file using akka-http in Scala. Later, i got the queries about the test cases for the same. Therefore, in this blog I am going to explain the way of writing test cases for file upload.

First we need to add test dependency :


"com.typesafe.akka" %% "akka-http-testkit" % "2.4.3",
"org.scalatest" %% "scalatest" % "2.2.6" % "test"

Full code :

package com.rishi

import java.io.File

import akka.http.scaladsl.model.{StatusCodes, Multipart, ContentTypes}
import akka.http.scaladsl.testkit.ScalatestRouteTest
import org.scalatest.{FlatSpec, Matchers}

class FileUploadSpec extends FlatSpec with Matchers with ScalatestRouteTest with FileUpload {
  override def testConfigSource = "akka.loglevel = WARNING"

  "File upload" should "not be able to upload file when file does not exist" in {
    val file = new File("")
    val formData = Multipart.FormData.fromFile("file", ContentTypes.`application/octet-stream`, file, 100000)
    Post(s"/user/upload/file", formData) -> routes -> check {
      status shouldBe StatusCodes.InternalServerError
      responseAs[String] shouldBe "Error in file uploading"
    }
  }

  it should "be able to upload file" in {
    val file = new File(getClass.getResource("/testFile").toString)
    val formData = Multipart.FormData.fromFile("file", ContentTypes.`application/octet-stream`, file, 100000)
    Post(s"/user/upload/file", formData) -> routes -> check {
      status shouldBe StatusCodes.OK
      responseAs[String] contains  "File successfully uploaded"
    }
  }
}

Get full code here.

It’s done. Hope you enjoy it. In my next blog, I will create a basic application to handle multipart formdata (file + form fields) using akka-http in Scala. So Stay tuned !!

Happy Blogging !!!

About Rishi Khandelwal

Lead Consultant having more than 6 years industry experience. He has working experience in various technologies such as Scala, Java8, Play, Akka, Lagom, Spark, Hive, Kafka, Cassandra, Akka-http, Akka-Streams, ElasticSearch, Backbone.js, html5, javascript, Less, Amazon EC2, WebRTC, SBT
This entry was posted in Scala. Bookmark the permalink.

4 Responses to Test cases for file upload using akka-http in Scala

  1. Pingback: A basic application to handle multipart form data using akka-http with test cases in Scala | Knoldus

  2. reddy sekhar says:

    Hi

    I have an Akka HTTP service like

    https://stackoverflow.com/q/48762297

    path( “file-upload”) {
    extractClientIP { ip =>
    optionalHeaderValueByName(Constants.AUTH) { auth =>
    (post & extractRequestContext) { request =>
    extractRequestContext {
    ctx => {
    implicit val materializer = ctx.materializer
    implicit val ec = ctx.executionContext
    val currentTime = TimeObject.getCurrentTime()
    fileUpload(“fileUpload”) {
    case (fileInfo, fileStream) =>
    val localPath = Configuration.excelFilePath
    val uniqueidString = “12345”
    val filename = uniqueidString + fileInfo.fileName
    val sink = FileIO.toPath(Paths.get(localPath) resolve filename)
    val writeResult = fileStream.runWith(sink)
    onSuccess(writeResult) { result =>
    result.status match {
    case Success(_) =>
    var excelPath = localPath + File.separator + uniqueidString + fileInfo.fileName
    var doc_count = itemsExcelParse(excelPath, companyCode, subCompanyId, userId)
    val currentTime2 = TimeObject.getCurrentTime()
    var upload_time = currentTime2 – currentTime
    val resp: JsValue = Json.toJson(doc_count)
    complete {
    val json: JsValue = Json.obj(“status” -> Constants.SUCCESS,
    “status_details” -> “null”, “upload_details” -> resp)
    HttpResponse(status = StatusCodes.OK, entity = HttpEntity(ContentType(MediaTypes.`application/json`), json.toString))
    }

    case Failure(e) =>
    complete {
    val json: JsValue = Json.obj(“status” -> Constants.ERROR)
    HttpResponse(status = StatusCodes.BandwidthLimitExceeded, entity = HttpEntity(ContentType(MediaTypes.`application/json`), json.toString))
    }
    }
    }
    }
    }
    }
    }
    }
    }
    }

    am using test code like

    it should “be able to upload file” in {
    val file = new File(getClass.getResource(“E:\\Excel\\1122 gr.xls”).toString)
    val formData = Multipart.FormData.fromFile(“fileUpload”, ContentTypes.`application/octet-stream`, file, 100000)
    Post(s”/api/file-upload”, formData).withHeaders(oauthHeader) ~> createPORoute -> check {
    status shouldBe StatusCodes.OK
    responseAs[String] contains “File successfully uploaded”
    }
    }

    but am getting the issue

    [info] – should be able to upload file *** FAILED ***
    [info] java.lang.NullPointerException:
    [info] at ExcelfileServiceSpec$$anonfun$1.apply$mcV$sp(ExcelfileServiceSpec.scala:34)
    [info] at ExcelfileServiceSpec$$anonfun$1.apply(ExcelfileServiceSpec.scala:33)
    [info] at ExcelfileServiceSpec$$anonfun$1.apply(ExcelfileServiceSpec.scala:33)
    [info] at org.scalatest.Transformer$$anonfun$apply$1.apply$mcV$sp(Transformer.scala:22)
    [info] at org.scalatest.OutcomeOf$class.outcomeOf(OutcomeOf.scala:85)
    [info] at org.scalatest.OutcomeOf$.outcomeOf(OutcomeOf.scala:104)
    [info] at org.scalatest.Transformer.apply(Transformer.scala:22)
    [info] at org.scalatest.Transformer.apply(Transformer.scala:20)
    [info] at org.scalatest.FlatSpecLike$$anon$1.apply(FlatSpecLike.scala:1647)
    [info] at org.scalatest.Suite$class.withFixture(Suite.scala:1122)

    how can I resolve the above issue

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s