How to validate the date received in the response in Karate BDD

Viewed 6521

I have two fields in the response having two parameters in response. { date1: "18-12-2018", date2: "23-11-2018" }

i want to test id date1 is less than today's date and date2 is less than some otherdate in request param. I dont know how this i can perform in karate schema validation

2 Answers

You need to parse the string date into a java date / long

* def toTime =
    """
    function(s) {
      var SimpleDateFormat = Java.type('java.text.SimpleDateFormat');
      var sdf = new SimpleDateFormat("dd-MM-yyyy");
      return sdf.parse(s).time           
    }
    """ 
* def other = "20-11-2018"
* def today = new java.util.Date().time
* def response = { date1: "18-12-2018", date2: "23-11-2018" }
* assert today > toTime(response.date1)
* assert toTime(other) < toTime(response.date2)

As an addendum to Peter Thomas's answer. Here is how I externalized it into a callable .feature file:

@ignore
Feature: Reusable function to capture info about the date

  # Example:
  # * def dateResponse = call read('classpath:features/test_getdate.feature')
  # * def todaysDate = dateResponse.today
  # * def lastYearDate = dateResponse.oneYearAgo

  Background: Setup
    * def pattern = 'MM/dd/yyyy'
    * def getDate =
      """
      function() {
        var SimpleDateFormat = Java.type('java.text.SimpleDateFormat');
        var sdf = new SimpleDateFormat(pattern);
        var date = new java.util.Date();
        return sdf.format(date);
      } 
      """

  Scenario: Capture todays date
    * def today = getDate()
    * karate.log("Today's date is: " + today )

  Scenario: Capture a year old date
    * def today = getDate()
    * def getSubtractedYear =
      """
      function(s) {
        var DateTimeFormatter = Java.type("java.time.format.DateTimeFormatter");
        var LocalDate = Java.type("java.time.LocalDate");
        var ChronoUnit = Java.type("java.time.temporal.ChronoUnit");
        var dtf = DateTimeFormatter.ofPattern(pattern);
        try {
          var adj = LocalDate.parse(today, dtf).minusMonths(12);
          return dtf.format(adj);
        } catch(e) {
          karate.log('*** date parse error: ', s);
        }
      } 
      """
    * def oneYearAgo = getSubtractedYear()
    * karate.log("One year ago is: " + oneYearAgo)

Then I test it like so:

@mysuite
Feature: Get information about the date

  Background: Setup
    * def dateResponse = call read('classpath:features/test_getdate.feature')

  Scenario: Extract todays date
    * def todaysDate = dateResponse.today
    * karate.log("Captured todays date: " + todaysDate)

  Scenario: Extract last years date
    * def lastYearDate = dateResponse.oneYearAgo
    * karate.log("Captured last years date: " + lastYearDate)
Related