package org.folio.rest.persist.cql;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.fail;

import org.folio.rest.persist.cql.CQLWrapper;
import org.junit.Test;
import org.z3950.zing.cql.cql2pgjson.CQL2PgJSON;
import org.z3950.zing.cql.cql2pgjson.FieldException;

public class CQLWrapperTest {
  @Test
  public void returnsWhere() throws FieldException {
    CQLWrapper wrapper = new CQLWrapper().setField(new CQL2PgJSON("field")).setQuery("name=miller");
    assertThat(wrapper.toString(), startsWith(" WHERE "));
  }

  @Test
  public void allRecords() throws FieldException {
    CQLWrapper wrapper = new CQLWrapper().setField(new CQL2PgJSON("field")).setQuery("cql.allRecords=1");
    assertThat(wrapper.toString(), is(" WHERE true"));
  }

  @Test(expected = IllegalStateException.class)
  public void invalidCQL() throws FieldException {
    CQLWrapper wrapper = new CQLWrapper().setField(new CQL2PgJSON("field")).setQuery("or name=miller");
    wrapper.toString();
  }

  @Test
  public void invalidCQLvalidation() throws FieldException {
    CQLWrapper wrapper = new CQLWrapper().setField(new CQL2PgJSON("field")).setQuery("or name=miller");
    try {
      wrapper.toString();
      fail("exception expected");
    }
    catch (CQLQueryValidationException e) {
      assertThat(e.getMessage(), allOf(containsString("ParseException"), containsString("unexpected relation")));
    }
  }

  @Test
  public void wrap() throws FieldException {
    CQLWrapper wrapper = new CQLWrapper().setField(new CQL2PgJSON("field")).setQuery("cql.allRecords=1");
    wrapper.addWrapper(wrapper);
    wrapper.addWrapper(wrapper, "or");
    assertThat(wrapper.toString(), is(" WHERE true and true or true"));
  }

  @Test
  public void sortBy() throws FieldException {
    CQL2PgJSON cql2pgJson = new CQL2PgJSON("field");
    CQLWrapper wrapper = new CQLWrapper().setField(cql2pgJson).setQuery("cql.allRecords=1 sortBy name");
    assertThat(wrapper.toString(), stringContainsInOrder(" WHERE true ORDER BY ", "name"));
  }
}

@@ -330,16 +330,79 @@
 ception;
+%0Aimport org.z3950.zing.cql.cql2pgjson.QueryValidationException;
 %0A%0Apublic
@@ -1522,24 +1522,406 @@
 %0A    %7D%0A  %7D%0A%0A
+  @Test%0A  public void emptyCqlQueryValidationException() throws FieldException %7B%0A    CQLWrapper wrapper = new CQLWrapper().setField(new CQL2PgJSON(%22field%22)).setQuery(%22%22);%0A    try %7B%0A      wrapper.toString();%0A      fail(%22exception expected%22);%0A    %7D%0A    catch (CQLQueryValidationException e) %7B%0A      assertThat(e.getCause(), is(instanceOf(QueryValidationException.class)));%0A    %7D%0A  %7D%0A%0A
   @Test%0A  pu

Add unit test emptyCqlQueryValidationException()