0

I wrote a verticle to read the multipart form data from the vertx filesystem using routingContext.fileUploads(). Now I want to write a testcase. I am trying to upload a file to vertx filesystem, so I can call my verticle to read the file from the filesystem and test my code.

STK
  • 93
  • 2
  • 12

2 Answers2

0

I understood how to write the file to File System. This is my code for it.

String fileName = "C:\test_file.txt";

String temp = vertx.fileSystem().createTempFileBlocking("", ""); // This creates a temp file in system temp directory
Path path = Paths.get(fileName);
byte[] data = Files.readAllBytes(path);
Buffer buffer = Buffer.buffer(data);
FileSystem fs = vertx.fileSystem();
fs.writeFileBlocking(temp, buffer);

Buffer read = vertx.fileSystem().readFileBlocking(temp);
vertx.fileSystem().readFile(temp, f -> {
  if (f.succeeded()) {
    System.out.println("File read");
}});
STK
  • 93
  • 2
  • 12
0

If you're using vertx web, you have to attach a BodyHandler to your router (don't forget to add the failureHandler):

router
        .post(UPLOAD_PATH)
        .handler(BodyHandler.create(true)
                .setHandleFileUploads(true)
                .setUploadsDirectory(uploadPath))
        .handler(this::handleUpload)
        .failureHandler(rc -> {
                LOGGER.error(String.format("Failure appears on upload request: %s", failure.get()));
        });

then you can have access via le context:

private void handleUpload(RoutingContext context) {
    ...

    FileUpload file = context.fileUploads().iterator().next();

    ...
}

Once you have copied the file to the path you want to, you can create a WebClient in your test and access the vert.x filesystem to see if file is there:

@Test
public void uploadTest(TestContext context) {
  Async async = context.async();

  WebClient client = WebClient.create(vertx);
  MultipartForm form = MultipartForm.create().binaryFileUpload(...);

  client
      .post(8080, "localhost", YOUR_PATH)
      .sendMultipartForm(form, ar -> {
        if (ar.succeeded()) {
          // Ok
          FileSystem fs = vertx.fileSystem();

          fs.readDir(tempFile.getAbsolutePath(), listOfFileR -> {
            if (listOfFileR.failed()) {
              context.verify(v -> fail("read dir failed", listOfFileR.cause()));
            }
            context.verify(v -> yourAssert());
            async.countDown();
          });

        } else {
          context.verify(v -> fail("Send file failed", ar.cause()));
        }
      });
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
Juan Ma
  • 1
  • 2