001package io.ebean.test;
002
003import io.ebeaninternal.api.SpiLogger;
004import io.ebeaninternal.server.logger.DSpiLogger;
005
006import java.util.List;
007
008/**
009 * Provides access to the messages logged to <code>io.ebean.SQL</code>.
010 * <p>
011 * This is here to allow easy access to the SQL that was executed during testing and
012 * if desired we can use that to perform asserts in tests.
013 * </p>
014 * <pre>{@code
015 *
016 *     // start capturing SQL log messages
017 *     LoggedSql.start();
018 *
019 *     List<Customer> customers =
020 *           Customer.find.where()
021 *             .name.ilike("rob%")
022 *             .findList();
023 *
024 *       assertNotNull(customers);
025 *
026 *     // perform an insert
027 *     new Product("ad", "asd").save()
028 *
029 *
030 *     // return the captured SQL log messages
031 *     // since LoggedSql.start()
032 *     List<String> sql = LoggedSql.stop();
033 *
034 *     assertThat(sql).hasSize(2);
035 *     assertThat(sql.get(0)).contains("from customer");
036 *     assertThat(sql.get(1)).contains("into product");
037 *
038 * }</pre>
039 */
040public class LoggedSql {
041
042  private static CaptureLogger sqlLogger;
043
044  /**
045   * Internal use - register the logger for <code>io.ebean.SQL</code>.
046   */
047  static SpiLogger register(DSpiLogger logger) {
048    if (sqlLogger == null) {
049      sqlLogger = new CaptureLogger(logger);
050    }
051    return sqlLogger;
052  }
053
054  /**
055   * Start the capture of the <code>io.ebean.SQL</code> messages.
056   */
057  public static List<String> start() {
058    return sqlLogger.start();
059  }
060
061  /**
062   * Stop the capture of the <code>io.ebean.SQL</code> messages and return the messages/sql
063   * that was captured since the call to start().
064   */
065  public static List<String> stop() {
066    return sqlLogger.stop();
067  }
068
069  /**
070   * Collect and return the messages/sql that was captured since the call to start() or collect().
071   * <p>
072   * Unlike stop() collection of messages will continue.
073   * </p>
074   */
075  public static List<String> collect() {
076    return sqlLogger.collect();
077  }
078
079}