├── .gitignore ├── .mvn └── wrapper │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── .travis.yml ├── CHANGELOG.md ├── LICENSE ├── README.md ├── jitpack.yml ├── mvnw ├── mvnw.cmd ├── pom.xml └── src ├── build ├── codesigning.asc.enc ├── publish-doc.sh ├── publish-jar.sh └── settings.xml ├── main ├── asciidoc │ ├── about.adoc │ ├── assert-query-assertj.adoc │ ├── assert-query-hamcrest.adoc │ ├── assert-query-simple.adoc │ ├── assert-query.adoc │ ├── development.adoc │ ├── docinfos │ │ └── index-docinfo.html │ ├── how-to-use.adoc │ ├── index.adoc │ └── installation.adoc └── java │ └── net │ └── ttddyy │ └── dsproxy │ └── asserts │ ├── BaseQueryExecution.java │ ├── BatchExecution.java │ ├── BatchExecutionEntry.java │ ├── BatchParameterHolder.java │ ├── CallableBatchExecution.java │ ├── CallableBatchExecutionEntry.java │ ├── CallableExecution.java │ ├── DataSourceAssertException.java │ ├── DefaultQueryExtractor.java │ ├── OutParameterHolder.java │ ├── ParameterByIndexHolder.java │ ├── ParameterByNameHolder.java │ ├── ParameterHolder.java │ ├── ParameterKeyValue.java │ ├── ParameterKeyValueUtils.java │ ├── PreparedBatchExecution.java │ ├── PreparedBatchExecutionEntry.java │ ├── PreparedExecution.java │ ├── ProxyTestDataSource.java │ ├── QueriesHolder.java │ ├── QueryExecution.java │ ├── QueryExecutionFactoryListener.java │ ├── QueryExtractor.java │ ├── QueryHolder.java │ ├── StatementBatchExecution.java │ ├── StatementExecution.java │ ├── assertj │ ├── AbstractExecutionAssert.java │ ├── CallableBatchExecutionAssert.java │ ├── CallableExecutionAssert.java │ ├── DataSourceAssertAssertions.java │ ├── PreparedBatchExecutionAssert.java │ ├── PreparedExecutionAssert.java │ ├── ProxyTestDataSourceAssert.java │ ├── QueryExecutionAssert.java │ ├── StatementBatchExecutionAssert.java │ ├── StatementExecutionAssert.java │ ├── data │ │ ├── ExecutionParameter.java │ │ └── ExecutionParameters.java │ └── helper │ │ ├── AbstractHelperAsserts.java │ │ ├── BatchExecutionEntryAsserts.java │ │ └── ExecutionParameterAsserts.java │ └── hamcrest │ ├── BatchParameterHolderAssertions.java │ ├── CompositeMatcher.java │ ├── DataSourceAssertMatchers.java │ ├── ExecutionType.java │ ├── ExecutionTypeMatcher.java │ ├── OutParameterHolderAssertions.java │ ├── ParameterHolderAssertions.java │ ├── ParameterHolderMatcher.java │ ├── ProxyTestDataSourceAssertions.java │ ├── QueriesHolderAssertions.java │ ├── QueryExecutionAssertions.java │ ├── QueryHolderAssertions.java │ └── SqlTypeMatcher.java └── test ├── java └── net │ └── ttddyy │ └── dsproxy │ └── asserts │ ├── DatabaseTestRule.java │ ├── ParameterKeyValueTest.java │ ├── ProxyTestDataSourceTest.java │ ├── QueryExecutionFactoryListenerTest.java │ ├── api │ ├── AssertJAssertionApiCheck.java │ ├── HamcrestAssertionApiCheck.java │ └── SimpleAssertionApiCheck.java │ ├── assertj │ ├── CallableBatchExecutionAssertTest.java │ ├── CallableExecutionAssertTest.java │ ├── PreparedBatchExecutionAssertTest.java │ ├── PreparedExecutionAssertTest.java │ ├── ProxyTestDataSourceAssertionsTest.java │ ├── QueryExecutionAssertTest.java │ ├── StatementBatchExecutionAssertTest.java │ └── StatementExecutionAssertTest.java │ └── hamcrest │ ├── BatchParameterHolderAssertionsTest.java │ ├── CallableExecutionTest.java │ ├── CompositeMatcherTest.java │ ├── ExecutionTypeMatcherTest.java │ ├── OutParameterHolderAssertionsTest.java │ ├── ParameterHolderAssertionsTest.java │ ├── ParameterHolderMatcherTest.java │ ├── PreparedBatchExecutionMatcherTest.java │ ├── PreparedExecutionTest.java │ ├── ProxyTestDataSourceAssertionsTest.java │ ├── QueriesHolderAssertionsTest.java │ ├── QueryExecutionAssertionsTest.java │ ├── QueryHolderTest.java │ ├── SqlTypeMatcherTest.java │ └── StatementExecutionTest.java └── resources └── db └── migration └── V1__initialize_database.sql /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | *.iml 3 | *.ipr 4 | *.iws 5 | .idea/ 6 | -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ttddyy/datasource-assert/2cf1ad31948e4e18b60483b67417ab68e61ffc10/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.0/apache-maven-3.5.0-bin.zip -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | 3 | jdk: 4 | - oraclejdk8 5 | 6 | cache: 7 | directories: 8 | - ~/.m2/repository 9 | 10 | env: 11 | global: 12 | # GH_TOKEN 13 | - secure: "oghAxUq0ZQttFWHIVw+vX1WHU4DGjy/vZP8qoHwSDsiGZvsUhEqs0Vecjf0EUdNewmfjtO4pyEns5utzwUPesIN9n2Oe5SKLMyiRWR9EtxUBjBVwqXKE47fBYZS+WpqTolhYlKFKACdxahGxk54UYARZ1oHj2kbMCKBRSNig6+GbIb+KAo10+UnBSSb06WffDQ46HEn6jCZoGAuXLiIuUPM/HEHHHULzQ4Ef6oB5veci6TzwxR/BF2XGLoIqDoccdp6Pb2vxDjXHZBDewPEnwTcTTXFxPZepuDFrG6BZgHE3STK4LDg50rd66Flah7MBh+MuQYiMKhgrVuGCFSHRnE7a0OpdExGiEoUaamexqUgoE7fPMjB5s5aZwsHTUaH+Msbce379bHW0ts+qfByQdnrvxasSaalpNqPn7ZlezJE9SO5dv7Ui4rzkLA5M6BQzLm1a/84Avnn5gQ01ABzO1h/T9bfoJNiZduBo55zm3ZzFjiUG2wo0qG8VUjzSaXnkjl6Px8qV4Zo+lv2fnJcAYLQoplpvonqj/1FyCCAq2tBm3kg0PP8IVUhbtMj308bJc44etPD/DfFDC0rRYXjWrf3hSg9eVOv4deDuw7BtsQWiOBRdTACNKBfK6v3acLIMvPQv+OYplXHAMi4XxYsUvHstB+Jq7l5GtblwoWQIzQ8=" 14 | # SONATYPE_USER 15 | - secure: "Bzn6UbylpECwTi1qJ4N0xfgReZxJcSVMRNloBYm/rpTuTjIpBRH+tHdSDcpxtStOBjW2/1v3FAj4gt2pe3vIu9VL97kBqzLzrpdFBodJOteI0l71GrEEfRAcG8ZJRvBVr8bkShFgZjSrJ0dF+Q/mpMzVJ64TbWHWPFeuTQvZbvAZqlUQjGLz0bVEXnJxtJ7XNe4I+AjcjZGppFUgLDYwoPhWQLYQ91TnKtxEgeAPO+pYaJaVmPyQikvVLoCh0H7BjwmwvxJPq6wdNS9IHlCwf8FaHTn5sH8Z75XO/k26IOQvXRCr13rhBRSEsnf0raG8Raf14e4+zGgKpdEhpEtTXkpYRYYjLYNn+VcTPAAi8kTDEmmf8Li95z8NPnlZrXNK5R1jucptktEpL9Bx6UEk7U9r/lY2Poma25VoCPf69iWVf2y66DZCZ9vhbaSWAFu/JoqlllMOfrSv07fxOT16ojl+m078uDPe333VKo+KLfXXyKjXJnAEYRPRvaq3DjC16xZUMbixL1EKfG2h7/l/BAAUdBGTUmFr7BrCDSGnAY/F3ixizVj9FLINKYQqNe0lx9pd4PVD1zCbPYw5BN8SHoCecPC3JsKP8+lCzcL4ZRV0QpUY8/5cr/mCfpcrWw2OEuW7jUmsy+10peUyDo8dyjB8sbkFc7FK5eMqxLunkYE=" 16 | # SONATYPE_PASS 17 | - secure: "OCI+2F/kJkaJoPJUldJDLw1adMXc0aOIfWA2tKPrTwWQMNKCYs59by2rKN9cadBXXk2HF72zCk5WlBfWSaXV0NpLOPhXOwj0UgJwlFjKrWWNdCy3/f8MRDgOJdfI8e//GuekFJxPVxFvAExWhJTqQr8CP4yQIH0uPBFNXgnZ+rpXutsvml3SKf/ZlIQjQXxZq1rCgMAVtZez6l0usE69TzkxD0Tixc9KjEzzh+Ymxg1KuEP9Uirf2OJ0UF/a5/PU4AicHDqVd8jHVKqNYd/dQR4o68t1PInFXgHShVhMFgNO9jxas9oV4zr8J58O6i2itw8O8+l5hrrO0uPDRLNEC9fnJpMFBAeVugknB9KsykCQM87x780LExhg1UW9RVUFuFwMGgYqu2dR9jlcJGM7rJNyOS+08KxTf/fqXmxgR3ufZL+Gz9JAu/sPsWUSE/rem+oZokL/B39Fr/gM4af2wbe+KsfuQUJoIAirhT8ob4Osgy22FPvx8m4URWhXebmDV9gQFbabGQ/azdEyj5ua3dioS1o4dyPzTbIIe7y0I4jtoZuhHqJ9Tp+lgylaP+SMh8HdbuUc6skZYDl4m6sA5s8qcbVdinb9/U1vZhEz3znxvizubfpNSmRen2znfCVMdzp94D6j6SabMm6My+S5HsTFMmX3wA7ZRiMCitCISbI=" 18 | # GPG_KEYNAME 19 | - secure: "V04jLenenZzWQjoOexPIbSCUaSjU2Bskv5VBw+Q8R3W3ShczHmiIPb2cpX/vwfJg7m58pzmXiWYPwGXtuOylQM9unFSHnvNPQIrglH2dqF7ga1LVChjAPZ0sGHilE9aJWfPHXeEspSJPg0cf5MZmFIUVl85qEswWzYTfi6Klhaw7yOetjD/z4AT4mjSAFWC72PogdlheIYgfTJ69TsaDtBOo+ldkXqAqHVkM7nYBMrv4dKqwRYcJ+tGo652tysSR2FVoDl5nUkFiIog2yH/qpqAHEQ38SBT9Cqy2tFwMO062BexE2wRxcvjYcU8/ayi3uePB08eucEiVNeKzLAnxJS7JwOTaR4zGlgTUk7e/wnRHt/RjuxUBN3Tsd1YIkovdTQF68u02rOfvT+Zjz+2UgTV3TX1qHIZjIvJZWoEQj5U/G9yrAnGxoGaK8K/2f5Xt7mdYfjX+KFDyqM8upds04r2N+RTFuvex5ogUUeTZEglVI4H8yAcx/RvknAVSbm6e4sO5HhozGmbgcEsCIqmAWdA4CMlRw3KgdCNFavmKWDKpculdAG4cTL/I9aZ7IoNBlHtf++9R7uHKTLz1XYPjnRdB21KXKWZxHJzvLE2OP/548GIx5YVVzpj0sVQMZpe6qUbyTzdsmxzywksmsh6Eh7R892gduLR9SsoGnVvtsLY=" 20 | # GPG_PASSPHRASE 21 | - secure: "IUdhc9gIZH0xlSeC6Bd+uQYUFXjqOXBtGl2CkKR00nibbUxUXuYhynxYqXYB+dAxLO9tNkqGWeBIPvYx+QCz7KTMj92i0pLdcjFS29HsjBDzvfKG/wcMf7Hp/58IW4H6t54N18K8weJNxOQ4AdatMPMnJGsiTyA7m9+pjtgMaBL5TMr8et6JgEsssfDH6WOngTIW0BqAEDFU9VdnxrBEJ+GOPTfJZpipeIFaPLmPftiD1biBIFN4kqbEhY/tz9ECPAypIm/kGcRezfNYOIlVUQHK1Kvd1G6QKMP3oiORFq2e+R6C0qqImJQj1xXd2DO8l6QduQV7N2v5wFpjQvj84GsVY9RtSg3w/KeTFYEmzsDGr6TI80iCGnG+Fj3DjcOob9pP1wDE0P6d/+UylyzYHAJsqLjz1/+B9rPvVBw0IoHDRqhcqXiibOhl8FOeuUTPKyzI/Kx/GiOnUBWloez6zmdttssYGqxhrPV8VvIKYKDDA5kDfggWkZtKO058Yh4M/eLfGEqDbjwSzkXW9wOz4fOwvyAm5nDN639fLVIjv6AC3ciXlY97BgN/bfJo/QGv6rsdclTna3d8ITGKBzw/JOYgDPn8hpI0ynidzZa7Df56T/SyAb8YNUVG74kEk/Q1uc333QFBjhNDvrVgDBJSqX2H7yE0y6t1weGYY2/l+BQ=" 22 | 23 | after_success: 24 | - bash ./src/build/publish-jar.sh 25 | - bash ./src/build/publish-doc.sh 26 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ttddyy/datasource-assert/2cf1ad31948e4e18b60483b67417ab68e61ffc10/CHANGELOG.md -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # datasource-assert 2 | 3 | ![Maven Central][badge-maven-central] 4 | 5 | `datasource-assert` provides assertion API for DataSource to validate query executions. 6 | 7 | The assertion API is used for assertion methods such as `assertEquals` in [JUnit][junit] and [TestNG][testng]. 8 | Also, it comes with support for `assertThat` in [AssertJ][assertj] and [Hamcrest][hamcrest]. 9 | 10 | 11 | ## Artifacts 12 | 13 | ### Released Version 14 | 15 | ```xml 16 | 17 | net.ttddyy 18 | datasource-assert 19 | [LATEST_VERSION] 20 | 21 | ``` 22 | 23 | ## Documentation 24 | 25 | - User Guide 26 | - [Latest Released Version][user-guide-latest] 27 | - [Snapshot Version][user-guide-snapshot] 28 | - Javadoc 29 | - [Latest Released Version][javadoc-latest] 30 | - [Snapshot Version][javadoc-snapshot] 31 | 32 | 33 | ## How to use 34 | 35 | Wrap your datasource with `ProxyTestDataSource`. 36 | 37 | ```java 38 | @Test 39 | public void myTest() { 40 | ProxyTestDataSource ds = new ProxyTestDataSource(actualDataSource); 41 | // rest of test 42 | } 43 | ``` 44 | 45 | If you want to reuse the same `ProxyTestDataSource` instance, you could `reset()` it between tests. 46 | 47 | ```java 48 | @After // @AfterEach, @AfterMethod 49 | public void tearDown() { 50 | this.ds.reset(); 51 | } 52 | ``` 53 | 54 | 55 | ### Regular assertions 56 | 57 | For normal assertions such as [JUnit][junit]/[TestNG][testng] `assertEquals`, use methods from `ProxyTestDataSource`. 58 | 59 | ```java 60 | assertEquals(3, ds.getQueryExecutions().size()); 61 | PreparedExecution pe = ds.getFirstPrepared(); 62 | assertTrue(pe.isSuccess()); 63 | ``` 64 | 65 | See more details on ["Usage examples"](#usage-examples). 66 | 67 | ### AssertJ 68 | 69 | Static import `assertThat` from `DataSourceAssertAssertions`. 70 | 71 | ```java 72 | import static net.ttddyy.dsproxy.asserts.assertj.DataSourceAssertAssertions.assertThat; 73 | ``` 74 | 75 | ```java 76 | assertThat(ds.getQueryExecutions()).hasSize(1); 77 | assertThat(ds.getQueryExecutions().get(0)).isStatement().asStatement().query().isEqualTo("SELECT id FROM emp"); 78 | assertThat(ds.getFirstPrepared()).containsParam(1, "foo"); 79 | ``` 80 | 81 | See more details on ["Usage examples"](#usage-examples). 82 | 83 | ### Hamcrest 84 | 85 | Use matchers from `DataSourceAssertMatchers`. 86 | 87 | ```java 88 | assertThat(ds, statementCount(3)); 89 | assertThat(ds, executions(1, is(statement()))); 90 | assertThat((StatementExecution) statements.get(0), query(is("SELECT id FROM emp"))); 91 | assertThat(ds.getFirstPrepared(), paramAsInteger(1, is(100))); 92 | ``` 93 | 94 | See more details on ["Usage examples"](#usage-examples). 95 | 96 | ## Usage examples 97 | 98 | ### Regular assertions(assertEquals, etc) 99 | - [SimpleAssertionApiCheck](../master/src/test/java/net/ttddyy/dsproxy/asserts/api/SimpleAssertionApiCheck.java) 100 | 101 | ### With AssertJ 102 | - [AssertJAssertionApiCheck](../master/src/test/java/net/ttddyy/dsproxy/asserts/api/AssertJAssertionApiCheck.java) 103 | 104 | ### With Hamcrest 105 | - [HamcrestAssertionApiCheck](../master/src/test/java/net/ttddyy/dsproxy/asserts/api/HamcrestAssertionApiCheck.java) 106 | 107 | 108 | ---- 109 | 110 | [badge-maven-central]: https://maven-badges.herokuapp.com/maven-central/net.ttddyy/datasource-assert/badge.svg 111 | [user-guide-latest]: https://ttddyy.github.io/datasource-assert/docs/current/user-guide/index.html 112 | [user-guide-snapshot]: https://ttddyy.github.io/datasource-assert/docs/snapshot/user-guide/index.html 113 | [javadoc-latest]: https://ttddyy.github.io/datasource-assert/docs/current/api/index.html 114 | [javadoc-snapshot]: https://ttddyy.github.io/datasource-assert/docs/snapshot/api/index.html 115 | [datasource-proxy]: https://github.com/ttddyy/datasource-proxy 116 | [junit]: http://junit.org/ 117 | [testng]: http://testng.org/ 118 | [assertj]: http://joel-costigliola.github.io/assertj/ 119 | [hamcrest]: http://hamcrest.org -------------------------------------------------------------------------------- /jitpack.yml: -------------------------------------------------------------------------------- 1 | # 2 | # config for https://jitpack.io 3 | # 4 | jdk: 5 | - oraclejdk8 -------------------------------------------------------------------------------- /mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven2 Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Mingw, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | # TODO classpath? 118 | fi 119 | 120 | if [ -z "$JAVA_HOME" ]; then 121 | javaExecutable="`which javac`" 122 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 123 | # readlink(1) is not available as standard on Solaris 10. 124 | readLink=`which readlink` 125 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 126 | if $darwin ; then 127 | javaHome="`dirname \"$javaExecutable\"`" 128 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 129 | else 130 | javaExecutable="`readlink -f \"$javaExecutable\"`" 131 | fi 132 | javaHome="`dirname \"$javaExecutable\"`" 133 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 134 | JAVA_HOME="$javaHome" 135 | export JAVA_HOME 136 | fi 137 | fi 138 | fi 139 | 140 | if [ -z "$JAVACMD" ] ; then 141 | if [ -n "$JAVA_HOME" ] ; then 142 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 143 | # IBM's JDK on AIX uses strange locations for the executables 144 | JAVACMD="$JAVA_HOME/jre/sh/java" 145 | else 146 | JAVACMD="$JAVA_HOME/bin/java" 147 | fi 148 | else 149 | JAVACMD="`which java`" 150 | fi 151 | fi 152 | 153 | if [ ! -x "$JAVACMD" ] ; then 154 | echo "Error: JAVA_HOME is not defined correctly." >&2 155 | echo " We cannot execute $JAVACMD" >&2 156 | exit 1 157 | fi 158 | 159 | if [ -z "$JAVA_HOME" ] ; then 160 | echo "Warning: JAVA_HOME environment variable is not set." 161 | fi 162 | 163 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 164 | 165 | # traverses directory structure from process work directory to filesystem root 166 | # first directory with .mvn subdirectory is considered project base directory 167 | find_maven_basedir() { 168 | 169 | if [ -z "$1" ] 170 | then 171 | echo "Path not specified to find_maven_basedir" 172 | return 1 173 | fi 174 | 175 | basedir="$1" 176 | wdir="$1" 177 | while [ "$wdir" != '/' ] ; do 178 | if [ -d "$wdir"/.mvn ] ; then 179 | basedir=$wdir 180 | break 181 | fi 182 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 183 | if [ -d "${wdir}" ]; then 184 | wdir=`cd "$wdir/.."; pwd` 185 | fi 186 | # end of workaround 187 | done 188 | echo "${basedir}" 189 | } 190 | 191 | # concatenates all lines of a file 192 | concat_lines() { 193 | if [ -f "$1" ]; then 194 | echo "$(tr -s '\n' ' ' < "$1")" 195 | fi 196 | } 197 | 198 | BASE_DIR=`find_maven_basedir "$(pwd)"` 199 | if [ -z "$BASE_DIR" ]; then 200 | exit 1; 201 | fi 202 | 203 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 204 | if [ "$MVNW_VERBOSE" = true ]; then 205 | echo $MAVEN_PROJECTBASEDIR 206 | fi 207 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 208 | 209 | # For Cygwin, switch paths to Windows format before running java 210 | if $cygwin; then 211 | [ -n "$M2_HOME" ] && 212 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 213 | [ -n "$JAVA_HOME" ] && 214 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 215 | [ -n "$CLASSPATH" ] && 216 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 217 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 218 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 219 | fi 220 | 221 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 222 | 223 | exec "$JAVACMD" \ 224 | $MAVEN_OPTS \ 225 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 226 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 227 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 228 | -------------------------------------------------------------------------------- /mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM http://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven2 Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' 39 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 40 | 41 | @REM set %HOME% to equivalent of $HOME 42 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 43 | 44 | @REM Execute a user defined script before this one 45 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 46 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 47 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 48 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 49 | :skipRcPre 50 | 51 | @setlocal 52 | 53 | set ERROR_CODE=0 54 | 55 | @REM To isolate internal variables from possible post scripts, we use another setlocal 56 | @setlocal 57 | 58 | @REM ==== START VALIDATION ==== 59 | if not "%JAVA_HOME%" == "" goto OkJHome 60 | 61 | echo. 62 | echo Error: JAVA_HOME not found in your environment. >&2 63 | echo Please set the JAVA_HOME variable in your environment to match the >&2 64 | echo location of your Java installation. >&2 65 | echo. 66 | goto error 67 | 68 | :OkJHome 69 | if exist "%JAVA_HOME%\bin\java.exe" goto init 70 | 71 | echo. 72 | echo Error: JAVA_HOME is set to an invalid directory. >&2 73 | echo JAVA_HOME = "%JAVA_HOME%" >&2 74 | echo Please set the JAVA_HOME variable in your environment to match the >&2 75 | echo location of your Java installation. >&2 76 | echo. 77 | goto error 78 | 79 | @REM ==== END VALIDATION ==== 80 | 81 | :init 82 | 83 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 84 | @REM Fallback to current working directory if not found. 85 | 86 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 87 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 88 | 89 | set EXEC_DIR=%CD% 90 | set WDIR=%EXEC_DIR% 91 | :findBaseDir 92 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 93 | cd .. 94 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 95 | set WDIR=%CD% 96 | goto findBaseDir 97 | 98 | :baseDirFound 99 | set MAVEN_PROJECTBASEDIR=%WDIR% 100 | cd "%EXEC_DIR%" 101 | goto endDetectBaseDir 102 | 103 | :baseDirNotFound 104 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 105 | cd "%EXEC_DIR%" 106 | 107 | :endDetectBaseDir 108 | 109 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 110 | 111 | @setlocal EnableExtensions EnableDelayedExpansion 112 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 113 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 114 | 115 | :endReadAdditionalConfig 116 | 117 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 118 | 119 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 120 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 121 | 122 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 123 | if ERRORLEVEL 1 goto error 124 | goto end 125 | 126 | :error 127 | set ERROR_CODE=1 128 | 129 | :end 130 | @endlocal & set ERROR_CODE=%ERROR_CODE% 131 | 132 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 133 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 134 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 135 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 136 | :skipRcPost 137 | 138 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 139 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 140 | 141 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 142 | 143 | exit /B %ERROR_CODE% 144 | -------------------------------------------------------------------------------- /src/build/codesigning.asc.enc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ttddyy/datasource-assert/2cf1ad31948e4e18b60483b67417ab68e61ffc10/src/build/codesigning.asc.enc -------------------------------------------------------------------------------- /src/build/publish-doc.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e # exit with nonzero exit code if anything fails 3 | 4 | if [ "$TRAVIS_PULL_REQUEST" != 'false' ]; then 5 | echo "Not publishing documents. Build triggered by pull request: ${TRAVIS_PULL_REQUEST_SLUG}"; 6 | exit 0; 7 | fi 8 | 9 | if [ "$TRAVIS_BRANCH" != 'master' ] && [ -z "$TRAVIS_TAG" ]; then 10 | echo "Not publishing documents. Build triggered from non-master branch: ${TRAVIS_BRANCH}"; 11 | exit 0; 12 | fi 13 | 14 | echo "Branch/Tag = ${TRAVIS_BRANCH}"; 15 | 16 | ./mvnw -Ppublish-doc asciidoctor:process-asciidoc@output-html javadoc:javadoc 17 | 18 | cd $HOME 19 | rm -fr gh-pages 20 | 21 | git config --global user.email "travis@travis-ci.org" 22 | git config --global user.name "travis-ci" 23 | git clone --quiet --branch=gh-pages https://${GH_TOKEN}@github.com/ttddyy/datasource-assert gh-pages > /dev/null 24 | 25 | cd gh-pages 26 | 27 | if [ "$TRAVIS_BRANCH" == 'master' ]; then 28 | echo "Adding snapshot documents" 29 | mkdir -p docs/snapshot/user-guide/ 30 | mkdir -p docs/snapshot/api/ 31 | cp -Rf $TRAVIS_BUILD_DIR/target/generated-docs/index.html docs/snapshot/user-guide/ 32 | cp -Rf $TRAVIS_BUILD_DIR/target/site/apidocs/* docs/snapshot/api/ 33 | else 34 | echo "Adding release documents to current and ${TRAVIS_TAG}" 35 | mkdir -p docs/current/user-guide/ 36 | mkdir -p docs/${TRAVIS_TAG}/user-guide/ 37 | mkdir -p docs/current/api/ 38 | mkdir -p docs/${TRAVIS_TAG}/api/ 39 | cp -Rf $TRAVIS_BUILD_DIR/target/generated-docs/index.html docs/${TRAVIS_TAG}/user-guide/ 40 | cp -Rf $TRAVIS_BUILD_DIR/target/generated-docs/index.html docs/current/user-guide/ 41 | cp -Rf $TRAVIS_BUILD_DIR/target/site/apidocs/* docs/${TRAVIS_TAG}/api/ 42 | cp -Rf $TRAVIS_BUILD_DIR/target/site/apidocs/* docs/current/api/ 43 | fi 44 | 45 | git add -f . 46 | git commit -m "Latest documentation on successful travis build $TRAVIS_BUILD_NUMBER auto-pushed to gh-pages" 47 | git push -fq origin gh-pages > /dev/null 48 | -------------------------------------------------------------------------------- /src/build/publish-jar.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -e # exit with nonzero exit code if anything fails 3 | 4 | if [ "$TRAVIS_PULL_REQUEST" != 'false' ]; then 5 | echo "Build triggered by pull request: ${TRAVIS_PULL_REQUEST_SLUG}"; 6 | exit 0; 7 | fi 8 | 9 | echo "Branch = ${TRAVIS_BRANCH}"; 10 | 11 | if [ "$TRAVIS_BRANCH" == 'master' ] || [ ! -z "$TRAVIS_TAG" ]; then 12 | openssl aes-256-cbc -K $encrypted_12c4c44010b8_key -iv $encrypted_12c4c44010b8_iv -in src/build/codesigning.asc.enc -out target/codesigning.asc -d 13 | gpg --fast-import target/codesigning.asc 14 | 15 | ./mvnw deploy --settings src/build/settings.xml -DskipTests=true 16 | fi 17 | 18 | 19 | -------------------------------------------------------------------------------- /src/build/settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | ossrh 8 | ${env.SONATYPE_USER} 9 | ${env.SONATYPE_PASS} 10 | 11 | 12 | 13 | 14 | 15 | 16 | ossrh 17 | 18 | gpg 19 | ${env.GPG_KEYNAME} 20 | ${env.GPG_PASSPHRASE} 21 | 22 | 23 | 24 | 25 | 26 | 27 | ossrh 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /src/main/asciidoc/about.adoc: -------------------------------------------------------------------------------- 1 | [[about]] 2 | == About 3 | 4 | `datasource-assert` provides assertion API for DataSource to validate query executions. 5 | 6 | The assertion API is used for assertion methods such as `assertEquals` in {junit}[JUnit] and {testng}[TestNG]. 7 | Also, it comes with support for `assertThat` in {assertj}[AssertJ] and {hamcrest}[Hamcrest]. 8 | 9 | Github project: {datasource-assert}[datasource-assert] 10 | 11 | -------------------------------------------------------------------------------- /src/main/asciidoc/assert-query-assertj.adoc: -------------------------------------------------------------------------------- 1 | [[assert-query-with-assertj]] 2 | === AssertJ 3 | 4 | This section describes how to assert `ProxyTestDataSource` with {assertj}[AssertJ]. 5 | 6 | 7 | [[assert-query-assertj-datasource]] 8 | ==== DataSource 9 | 10 | [source,java,indent=0] 11 | ---- 12 | include::{testDir}/net/ttddyy/dsproxy/asserts/api/AssertJAssertionApiCheck.java[tags=datasource] 13 | ---- 14 | 15 | 16 | [[assert-query-assertj-query]] 17 | ==== Query Executions 18 | 19 | [source,java,indent=0] 20 | ---- 21 | include::{testDir}/net/ttddyy/dsproxy/asserts/api/AssertJAssertionApiCheck.java[tags=query] 22 | ---- 23 | 24 | 25 | [[assert-query-assertj-statement]] 26 | ==== Statement 27 | 28 | [source,java,indent=0] 29 | ---- 30 | include::{testDir}/net/ttddyy/dsproxy/asserts/api/AssertJAssertionApiCheck.java[tags=statement] 31 | ---- 32 | 33 | 34 | [[assert-query-assertj-batch-statement]] 35 | ==== Batch Statement 36 | 37 | [source,java,indent=0] 38 | ---- 39 | include::{testDir}/net/ttddyy/dsproxy/asserts/api/AssertJAssertionApiCheck.java[tags=batch-statement] 40 | ---- 41 | 42 | 43 | [[assert-query-assertj-prepared]] 44 | ==== Prepared Statement 45 | 46 | [source,java,indent=0] 47 | ---- 48 | include::{testDir}/net/ttddyy/dsproxy/asserts/api/AssertJAssertionApiCheck.java[tags=prepared] 49 | ---- 50 | 51 | 52 | [[assert-query-assertj-batch-prepared]] 53 | ==== Batch Prepared Statement 54 | 55 | [source,java,indent=0] 56 | ---- 57 | include::{testDir}/net/ttddyy/dsproxy/asserts/api/AssertJAssertionApiCheck.java[tags=batch-prepared] 58 | ---- 59 | 60 | 61 | [[assert-query-assertj-callable]] 62 | ==== Callable Statement 63 | 64 | [source,java,indent=0] 65 | ---- 66 | include::{testDir}/net/ttddyy/dsproxy/asserts/api/AssertJAssertionApiCheck.java[tags=callable] 67 | ---- 68 | 69 | 70 | [[assert-query-assertj-batch-prepared]] 71 | ==== Batch Callable Statement 72 | 73 | [source,java,indent=0] 74 | ---- 75 | include::{testDir}/net/ttddyy/dsproxy/asserts/api/AssertJAssertionApiCheck.java[tags=batch-callable] 76 | ---- 77 | 78 | 79 | -------------------------------------------------------------------------------- /src/main/asciidoc/assert-query-hamcrest.adoc: -------------------------------------------------------------------------------- 1 | [[assert-query-with-hamcrest]] 2 | === Hamcrest 3 | 4 | This section describes how to assert `ProxyTestDataSource` with {hamcrest}[Hamcrest]. 5 | 6 | 7 | [[assert-query-hamcrest-datasource]] 8 | ==== DataSource 9 | 10 | [source,java,indent=0] 11 | ---- 12 | include::{testDir}/net/ttddyy/dsproxy/asserts/api/HamcrestAssertionApiCheck.java[tags=datasource] 13 | ---- 14 | 15 | 16 | [[assert-query-hamcrest-query]] 17 | ==== Query Executions 18 | 19 | [source,java,indent=0] 20 | ---- 21 | include::{testDir}/net/ttddyy/dsproxy/asserts/api/HamcrestAssertionApiCheck.java[tags=query] 22 | ---- 23 | 24 | 25 | [[assert-query-hamcrest-statement]] 26 | ==== Statement 27 | 28 | [source,java,indent=0] 29 | ---- 30 | include::{testDir}/net/ttddyy/dsproxy/asserts/api/HamcrestAssertionApiCheck.java[tags=statement] 31 | ---- 32 | 33 | 34 | [[assert-query-hamcrest-batch-statement]] 35 | ==== Batch Statement 36 | 37 | [source,java,indent=0] 38 | ---- 39 | include::{testDir}/net/ttddyy/dsproxy/asserts/api/HamcrestAssertionApiCheck.java[tags=batch-statement] 40 | ---- 41 | 42 | 43 | [[assert-query-hamcrest-prepared]] 44 | ==== Prepared Statement 45 | 46 | [source,java,indent=0] 47 | ---- 48 | include::{testDir}/net/ttddyy/dsproxy/asserts/api/HamcrestAssertionApiCheck.java[tags=prepared] 49 | ---- 50 | 51 | 52 | [[assert-query-hamcrest-batch-prepared]] 53 | ==== Batch Prepared Statement 54 | 55 | [source,java,indent=0] 56 | ---- 57 | include::{testDir}/net/ttddyy/dsproxy/asserts/api/HamcrestAssertionApiCheck.java[tags=batch-prepared] 58 | ---- 59 | 60 | 61 | [[assert-query-hamcrest-callable]] 62 | ==== Callable Statement 63 | 64 | [source,java,indent=0] 65 | ---- 66 | include::{testDir}/net/ttddyy/dsproxy/asserts/api/HamcrestAssertionApiCheck.java[tags=callable] 67 | ---- 68 | 69 | 70 | [[assert-query-hamcrest-batch-callable]] 71 | ==== Batch Callable Statement 72 | 73 | [source,java,indent=0] 74 | ---- 75 | include::{testDir}/net/ttddyy/dsproxy/asserts/api/HamcrestAssertionApiCheck.java[tags=batch-callable] 76 | ---- 77 | 78 | 79 | -------------------------------------------------------------------------------- /src/main/asciidoc/assert-query-simple.adoc: -------------------------------------------------------------------------------- 1 | [[assert-query-with-assertequals]] 2 | === assertEquals 3 | 4 | This section describes how to assert `ProxyTestDataSource` with simple `assertEquals` from {junit}[JUnit] or 5 | {testng}[TestNG]. 6 | 7 | All assertion examples below use JUnit4 `assertEquals`. 8 | 9 | 10 | [[assert-query-simple-datasource]] 11 | ==== DataSource 12 | 13 | [source,java,indent=0] 14 | ---- 15 | include::{testDir}/net/ttddyy/dsproxy/asserts/api/SimpleAssertionApiCheck.java[tags=datasource] 16 | ---- 17 | 18 | 19 | [[assert-query-simple-query]] 20 | ==== Query Executions 21 | 22 | [source,java,indent=0] 23 | ---- 24 | include::{testDir}/net/ttddyy/dsproxy/asserts/api/SimpleAssertionApiCheck.java[tags=query] 25 | ---- 26 | 27 | 28 | [[assert-query-simple-statement]] 29 | ==== Statement 30 | 31 | [source,java,indent=0] 32 | ---- 33 | include::{testDir}/net/ttddyy/dsproxy/asserts/api/SimpleAssertionApiCheck.java[tags=statement] 34 | ---- 35 | 36 | 37 | [[assert-query-simple-batch-statement]] 38 | ==== Batch Statement 39 | 40 | [source,java,indent=0] 41 | ---- 42 | include::{testDir}/net/ttddyy/dsproxy/asserts/api/SimpleAssertionApiCheck.java[tags=batch-statement] 43 | ---- 44 | 45 | 46 | [[assert-query-simple-prepared]] 47 | ==== Prepared Statement 48 | 49 | [source,java,indent=0] 50 | ---- 51 | include::{testDir}/net/ttddyy/dsproxy/asserts/api/SimpleAssertionApiCheck.java[tags=prepared] 52 | ---- 53 | 54 | 55 | [[assert-query-simple-batch-prepared]] 56 | ==== Batch Prepared Statement 57 | 58 | [source,java,indent=0] 59 | ---- 60 | include::{testDir}/net/ttddyy/dsproxy/asserts/api/SimpleAssertionApiCheck.java[tags=batch-prepared] 61 | ---- 62 | 63 | 64 | [[assert-query-simple-callable]] 65 | ==== Callable Statement 66 | 67 | [source,java,indent=0] 68 | ---- 69 | include::{testDir}/net/ttddyy/dsproxy/asserts/api/SimpleAssertionApiCheck.java[tags=callable] 70 | ---- 71 | 72 | 73 | [[assert-query-simple-batch-callable]] 74 | ==== Batch Callable Statement 75 | 76 | [source,java,indent=0] 77 | ---- 78 | include::{testDir}/net/ttddyy/dsproxy/asserts/api/SimpleAssertionApiCheck.java[tags=batch-callable] 79 | ---- 80 | 81 | -------------------------------------------------------------------------------- /src/main/asciidoc/assert-query.adoc: -------------------------------------------------------------------------------- 1 | [[assert-query-executions]] 2 | == Assert Query Executions 3 | 4 | include::assert-query-simple.adoc[] 5 | 6 | include::assert-query-assertj.adoc[] 7 | 8 | include::assert-query-hamcrest.adoc[] 9 | 10 | -------------------------------------------------------------------------------- /src/main/asciidoc/development.adoc: -------------------------------------------------------------------------------- 1 | [[development]] 2 | == Development 3 | 4 | Source code repository: {datasource-assert}[datasource-assert] 5 | 6 | === Build Source 7 | 8 | ```sh 9 | > ./mvnw install 10 | ``` 11 | 12 | === Build Documentation 13 | 14 | Generate `index.html` 15 | 16 | ```sh 17 | > ./mvnw asciidoctor:process-asciidoc@output-html 18 | ``` 19 | 20 | Http preview 21 | 22 | ```sh 23 | > ./mvnw asciidoctor:http@output-html 24 | ``` 25 | 26 | === Documentation 27 | 28 | * User Guide 29 | ** {user-guide-latest}[Latest released version] 30 | ** {user-guide-snapshot}[Snapshot version] 31 | 32 | * JavaDoc 33 | ** {javadoc-latest}[Latest released version] 34 | ** {javadoc-snapshot}[Snapshot version] 35 | 36 | -------------------------------------------------------------------------------- /src/main/asciidoc/docinfos/index-docinfo.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 10 | -------------------------------------------------------------------------------- /src/main/asciidoc/how-to-use.adoc: -------------------------------------------------------------------------------- 1 | [[how-to-use]] 2 | == How to use 3 | 4 | `datasource-assert` provides `ProxyTestDataSource` class that wraps your actual `DataSource` and provides 5 | assertion APIs. 6 | 7 | ```java 8 | // Create a DataSource for test 9 | ProxyTestDataSource ds = new ProxyTestDataSource(actualDataSource); 10 | 11 | // perform application logic using above "ds" as its DataSource 12 | 13 | // verify query interaction with assertEquals, AssertJ, Hamcrest 14 | assertEquals("num of executed queries", 3, ds.getQueryExecutions().size()); 15 | assertThat(ds.getFirstStatement(), query(startsWith("SELECT * FROM"))); // with Hamcrest 16 | assertThat(ds.getFirstStatement()).hasQueryType(QueryType.SELECT); // with AssertJ 17 | ``` 18 | 19 | See more details on <> 20 | 21 | 22 | [[how-to-use-assertj]] 23 | === With AssertJ 24 | For {assertj}[AssertJ], `DataSourceAssertAssertions` defines all `assertThat` methods and entry 25 | point methods. + 26 | To use them, static import those methods. 27 | 28 | ```java 29 | import static net.ttddyy.dsproxy.asserts.assertj.DataSourceAssertAssertions.assertThat; 30 | ``` 31 | 32 | See more details on <> 33 | 34 | [[how-to-use-hamcrest]] 35 | === With Hamcrest 36 | 37 | For {hamcrest}[Hamcrest], all matchers are defined in `DataSourceAssertMatchers` class. 38 | 39 | See more details on <> 40 | 41 | -------------------------------------------------------------------------------- /src/main/asciidoc/index.adoc: -------------------------------------------------------------------------------- 1 | = datasource-assert User Guide 2 | Tadaya Tsuyukubo 3 | // ====================================================================================== 4 | :sectnums: 5 | :docinfodir: docinfos 6 | :toclevels: 3 7 | // 8 | // add analytics only when publishing docs to github 9 | ifdef::insert-analytics[] 10 | :docinfo: private-head 11 | endif::[] 12 | 13 | :oss-snapshot-repository: https://oss.sonatype.org/content/repositories/snapshots/net/ttddyy/datasource-assert/ 14 | :datasource-assert: https://github.com/ttddyy/datasource-assert/ 15 | :datasource-proxy: https://github.com/ttddyy/datasource-proxy/ 16 | :user-guide-latest: https://ttddyy.github.io/datasource-assert/docs/latest/user-guide/index.html 17 | :user-guide-snapshot: https://ttddyy.github.io/datasource-assert/docs/snapshot/user-guide/index.html 18 | :javadoc-latest: https://ttddyy.github.io/datasource-assert/docs/latest/api/index.html 19 | :javadoc-snapshot: https://ttddyy.github.io/datasource-assert/docs/snapshot/api/index.html 20 | :junit: http://junit.org/ 21 | :testng: http://testng.org/ 22 | :assertj: http://joel-costigliola.github.io/assertj/ 23 | :hamcrest: http://hamcrest.org/JavaHamcrest/ 24 | 25 | include::about.adoc[] 26 | include::installation.adoc[] 27 | include::how-to-use.adoc[] 28 | include::assert-query.adoc[] 29 | include::development.adoc[] 30 | -------------------------------------------------------------------------------- /src/main/asciidoc/installation.adoc: -------------------------------------------------------------------------------- 1 | [[installation]] 2 | == Installation 3 | 4 | === Dependency 5 | 6 | ```xml 7 | 8 | net.ttddyy 9 | datasource-assert 10 | [LATEST_VERSION] 11 | 12 | ``` 13 | 14 | {datasource-proxy}[datasource-proxy] is the only dependent library. + 15 | {assertj}[AssertJ] and {hamcrest}[Hamcrest] are optional. 16 | To use those assertion libraries, explicit dependency needs to be specified in your project. 17 | 18 | 19 | ==== Snapshot (via Sonatype OSSRH) 20 | 21 | Snapshot is available via {oss-snapshot-repository}[oss sonatype snapshot repository]. 22 | 23 | To download snapshot jars, enable sonatype snapshot repository: 24 | 25 | ```xml 26 | 27 | 28 | sonatype-snapshots-repo 29 | https://oss.sonatype.org/content/repositories/snapshots 30 | 31 | false 32 | 33 | 34 | true 35 | 36 | 37 | 38 | ``` 39 | 40 | ==== Snapshot (via JitPack) 41 | 42 | ```xml 43 | 44 | 45 | jitpack.io 46 | https://jitpack.io 47 | 48 | 49 | ``` 50 | 51 | ```xml 52 | 53 | om.github.ttddyy 54 | datasource-assert 55 | master-SNAPSHOT 56 | 57 | ``` 58 | 59 | === Supported Java Versions 60 | 61 | `datasource-assert` works with java 1.7+. 62 | 63 | -------------------------------------------------------------------------------- /src/main/java/net/ttddyy/dsproxy/asserts/BaseQueryExecution.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts; 2 | 3 | /** 4 | * Base implementation class for {@link QueryExecution}. 5 | * 6 | * @author Tadaya Tsuyukubo 7 | * @since 1.0 8 | */ 9 | public abstract class BaseQueryExecution implements QueryExecution { 10 | 11 | private boolean success; 12 | 13 | public void setSuccess(boolean success) { 14 | this.success = success; 15 | } 16 | 17 | @Override 18 | public boolean isSuccess() { 19 | return this.success; 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/net/ttddyy/dsproxy/asserts/BatchExecution.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts; 2 | 3 | /** 4 | * Interface to represent batch execution. 5 | * 6 | * @author Tadaya Tsuyukubo 7 | * @since 1.0 8 | */ 9 | public interface BatchExecution { 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/net/ttddyy/dsproxy/asserts/BatchExecutionEntry.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts; 2 | 3 | /** 4 | * Represent each batch entry. 5 | * 6 | * @author Tadaya Tsuyukubo 7 | * @since 1.0 8 | */ 9 | public interface BatchExecutionEntry { 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/net/ttddyy/dsproxy/asserts/BatchParameterHolder.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts; 2 | 3 | import java.util.List; 4 | 5 | /** 6 | * Represent execution that hold batched batch parameters. 7 | * 8 | * @author Tadaya Tsuyukubo 9 | * @since 1.0 10 | */ 11 | public interface BatchParameterHolder { 12 | List getBatchExecutionEntries(); 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/net/ttddyy/dsproxy/asserts/CallableBatchExecution.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * Represent a single batch execution of {@link java.sql.CallableStatement}. 8 | * 9 | * @author Tadaya Tsuyukubo 10 | * @since 1.0 11 | */ 12 | public class CallableBatchExecution extends BaseQueryExecution implements BatchParameterHolder, QueryHolder, BatchExecution { 13 | 14 | private String query; 15 | 16 | private List batchExecutionEntries = new ArrayList<>(); 17 | 18 | @Override 19 | public boolean isBatch() { 20 | return true; 21 | } 22 | 23 | public void setQuery(String query) { 24 | this.query = query; 25 | } 26 | 27 | @Override 28 | public String getQuery() { 29 | return this.query; 30 | } 31 | 32 | @Override 33 | public List getBatchExecutionEntries() { 34 | return this.batchExecutionEntries; 35 | } 36 | 37 | public boolean addBatchExecutionEntry(CallableBatchExecutionEntry entry) { 38 | return this.batchExecutionEntries.add(entry); 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/net/ttddyy/dsproxy/asserts/CallableBatchExecutionEntry.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts; 2 | 3 | import net.ttddyy.dsproxy.proxy.ParameterKey; 4 | 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | import java.util.Map; 8 | import java.util.SortedSet; 9 | import java.util.TreeSet; 10 | 11 | import static net.ttddyy.dsproxy.asserts.ParameterKeyValueUtils.filterBy; 12 | import static net.ttddyy.dsproxy.asserts.ParameterKeyValueUtils.filterByKeyType; 13 | import static net.ttddyy.dsproxy.asserts.ParameterKeyValueUtils.toKeyIndexMap; 14 | import static net.ttddyy.dsproxy.asserts.ParameterKeyValueUtils.toKeyNameMap; 15 | 16 | /** 17 | * Represent a single batch execution of {@link java.sql.CallableStatement}. 18 | * 19 | * @author Tadaya Tsuyukubo 20 | * @since 1.0 21 | */ 22 | public class CallableBatchExecutionEntry implements BatchExecutionEntry, ParameterByIndexHolder, ParameterByNameHolder, OutParameterHolder { 23 | 24 | private SortedSet parameters = new TreeSet<>(); 25 | 26 | @Override 27 | public SortedSet getAllParameters() { 28 | return this.parameters; 29 | } 30 | 31 | @Override 32 | public SortedSet getSetParams() { 33 | return filterBy(this.parameters, ParameterKeyValue.OperationType.SET_PARAM); 34 | } 35 | 36 | @Override 37 | public SortedSet getSetNullParams() { 38 | return filterBy(this.parameters, ParameterKeyValue.OperationType.SET_NULL); 39 | } 40 | 41 | @Override 42 | public SortedSet getOutParams() { 43 | return filterBy(this.parameters, ParameterKeyValue.OperationType.REGISTER_OUT); 44 | } 45 | 46 | @Override 47 | public Map getSetParamsByName() { 48 | return toKeyNameMap(filterByKeyType(getSetParams(), ParameterKey.ParameterKeyType.BY_NAME)); 49 | } 50 | 51 | @Override 52 | public Map getSetParamsByIndex() { 53 | return toKeyIndexMap( 54 | filterByKeyType(getSetParams(), ParameterKey.ParameterKeyType.BY_INDEX)); 55 | } 56 | 57 | @Override 58 | public Map getSetNullParamsByName() { 59 | return toKeyNameMap( 60 | filterByKeyType(getSetNullParams(), ParameterKey.ParameterKeyType.BY_NAME)); 61 | } 62 | 63 | @Override 64 | public Map getSetNullParamsByIndex() { 65 | return toKeyIndexMap( 66 | filterByKeyType(getSetNullParams(), ParameterKey.ParameterKeyType.BY_INDEX)); 67 | 68 | } 69 | 70 | @Override 71 | public Map getOutParamsByName() { 72 | return toKeyNameMap(filterByKeyType(getOutParams(), ParameterKey.ParameterKeyType.BY_NAME)); 73 | } 74 | 75 | @Override 76 | public Map getOutParamsByIndex() { 77 | return toKeyIndexMap( 78 | filterByKeyType(getOutParams(), ParameterKey.ParameterKeyType.BY_INDEX)); 79 | } 80 | 81 | @Override 82 | public List getParamNames() { 83 | List names = new ArrayList<>(); 84 | names.addAll(getSetParamsByName().keySet()); 85 | names.addAll(getSetNullParamsByName().keySet()); 86 | return names; 87 | } 88 | 89 | @Override 90 | public List getParamIndexes() { 91 | List indexes = new ArrayList<>(); 92 | indexes.addAll(getSetParamsByIndex().keySet()); 93 | indexes.addAll(getSetNullParamsByIndex().keySet()); 94 | return indexes; 95 | } 96 | 97 | @Override 98 | public List getOutParamNames() { 99 | return new ArrayList<>(getOutParamsByName().keySet()); 100 | } 101 | 102 | @Override 103 | public List getOutParamIndexes() { 104 | return new ArrayList<>(getOutParamsByIndex().keySet()); 105 | } 106 | 107 | } 108 | -------------------------------------------------------------------------------- /src/main/java/net/ttddyy/dsproxy/asserts/CallableExecution.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts; 2 | 3 | import net.ttddyy.dsproxy.proxy.ParameterKey; 4 | 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | import java.util.Map; 8 | import java.util.SortedSet; 9 | import java.util.TreeSet; 10 | 11 | import static net.ttddyy.dsproxy.asserts.ParameterKeyValueUtils.filterBy; 12 | import static net.ttddyy.dsproxy.asserts.ParameterKeyValueUtils.filterByKeyType; 13 | import static net.ttddyy.dsproxy.asserts.ParameterKeyValueUtils.toKeyIndexMap; 14 | import static net.ttddyy.dsproxy.asserts.ParameterKeyValueUtils.toKeyNameMap; 15 | 16 | /** 17 | * Represent a single execution of {@link java.sql.CallableStatement}. 18 | * 19 | * @author Tadaya Tsuyukubo 20 | * @since 1.0 21 | */ 22 | public class CallableExecution extends BaseQueryExecution implements QueryHolder, ParameterByIndexHolder, ParameterByNameHolder, OutParameterHolder { 23 | 24 | private String query; 25 | private SortedSet parameters = new TreeSet<>(); 26 | 27 | 28 | @Override 29 | public boolean isBatch() { 30 | return false; 31 | } 32 | 33 | @Override 34 | public String getQuery() { 35 | return this.query; 36 | } 37 | 38 | public void setQuery(String query) { 39 | this.query = query; 40 | } 41 | 42 | @Override 43 | public SortedSet getAllParameters() { 44 | return this.parameters; 45 | } 46 | 47 | @Override 48 | public SortedSet getSetParams() { 49 | return filterBy(this.parameters, ParameterKeyValue.OperationType.SET_PARAM); 50 | } 51 | 52 | @Override 53 | public SortedSet getSetNullParams() { 54 | return filterBy(this.parameters, ParameterKeyValue.OperationType.SET_NULL); 55 | } 56 | 57 | @Override 58 | public SortedSet getOutParams() { 59 | return filterBy(this.parameters, ParameterKeyValue.OperationType.REGISTER_OUT); 60 | } 61 | 62 | @Override 63 | public Map getSetParamsByName() { 64 | return toKeyNameMap(filterByKeyType(getSetParams(), ParameterKey.ParameterKeyType.BY_NAME)); 65 | } 66 | 67 | @Override 68 | public Map getSetParamsByIndex() { 69 | return toKeyIndexMap(filterByKeyType(getSetParams(), ParameterKey.ParameterKeyType.BY_INDEX)); 70 | } 71 | 72 | @Override 73 | public Map getSetNullParamsByName() { 74 | return toKeyNameMap(filterByKeyType(getSetNullParams(), ParameterKey.ParameterKeyType.BY_NAME)); 75 | } 76 | 77 | @Override 78 | public Map getSetNullParamsByIndex() { 79 | return toKeyIndexMap(filterByKeyType(getSetNullParams(), ParameterKey.ParameterKeyType.BY_INDEX)); 80 | } 81 | 82 | @Override 83 | public Map getOutParamsByName() { 84 | return toKeyNameMap(filterByKeyType(getOutParams(), ParameterKey.ParameterKeyType.BY_NAME)); 85 | } 86 | 87 | @Override 88 | public Map getOutParamsByIndex() { 89 | return toKeyIndexMap(filterByKeyType(getOutParams(), ParameterKey.ParameterKeyType.BY_INDEX)); 90 | } 91 | 92 | @Override 93 | public List getParamNames() { 94 | List names = new ArrayList<>(); 95 | names.addAll(getSetParamsByName().keySet()); 96 | names.addAll(getSetNullParamsByName().keySet()); 97 | return names; 98 | } 99 | 100 | @Override 101 | public List getParamIndexes() { 102 | List indexes = new ArrayList<>(); 103 | indexes.addAll(getSetParamsByIndex().keySet()); 104 | indexes.addAll(getSetNullParamsByIndex().keySet()); 105 | return indexes; 106 | } 107 | 108 | @Override 109 | public List getOutParamNames() { 110 | return new ArrayList<>(getOutParamsByName().keySet()); 111 | } 112 | 113 | @Override 114 | public List getOutParamIndexes() { 115 | return new ArrayList<>(getOutParamsByIndex().keySet()); 116 | } 117 | 118 | } 119 | -------------------------------------------------------------------------------- /src/main/java/net/ttddyy/dsproxy/asserts/DataSourceAssertException.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts; 2 | 3 | /** 4 | * Framework exception from datasource-assert. 5 | * 6 | * @author Tadaya Tsuyukubo 7 | * @since 1.0 8 | */ 9 | public class DataSourceAssertException extends RuntimeException { 10 | 11 | public DataSourceAssertException() { 12 | } 13 | 14 | public DataSourceAssertException(String message) { 15 | super(message); 16 | } 17 | 18 | public DataSourceAssertException(String message, Throwable cause) { 19 | super(message, cause); 20 | } 21 | 22 | public DataSourceAssertException(Throwable cause) { 23 | super(cause); 24 | } 25 | 26 | public DataSourceAssertException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { 27 | super(message, cause, enableSuppression, writableStackTrace); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/net/ttddyy/dsproxy/asserts/DefaultQueryExtractor.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * @author Tadaya Tsuyukubo 8 | * @since 1.0 9 | */ 10 | public class DefaultQueryExtractor implements QueryExtractor { 11 | 12 | @Override 13 | public List getQueries(QueryExecution queryExecution) { 14 | List queries = new ArrayList<>(); 15 | if (queryExecution instanceof QueryHolder) { 16 | queries.add(((QueryHolder) queryExecution).getQuery()); 17 | } else if (queryExecution instanceof QueriesHolder) { 18 | queries.addAll(((QueriesHolder) queryExecution).getQueries()); 19 | } 20 | return queries; 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/net/ttddyy/dsproxy/asserts/OutParameterHolder.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts; 2 | 3 | import java.util.List; 4 | import java.util.Map; 5 | import java.util.SortedSet; 6 | 7 | /** 8 | * Represent an execution that hold out parameter. 9 | * 10 | * @author Tadaya Tsuyukubo 11 | * @since 1.0 12 | */ 13 | public interface OutParameterHolder extends ParameterHolder { 14 | 15 | SortedSet getOutParams(); 16 | 17 | Map getOutParamsByIndex(); 18 | 19 | Map getOutParamsByName(); 20 | 21 | /** 22 | * Keys of out parameters. 23 | * 24 | * @return Integer keys. 25 | */ 26 | List getOutParamIndexes(); 27 | 28 | /** 29 | * Keys of out parameters. 30 | * 31 | * @return String keys. 32 | */ 33 | List getOutParamNames(); 34 | 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/net/ttddyy/dsproxy/asserts/ParameterByIndexHolder.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts; 2 | 3 | import java.util.List; 4 | import java.util.Map; 5 | 6 | /** 7 | * Represent an execution that hold parameter by index. 8 | * 9 | * @author Tadaya Tsuyukubo 10 | * @since 1.0 11 | */ 12 | public interface ParameterByIndexHolder extends ParameterHolder { 13 | 14 | Map getSetParamsByIndex(); 15 | 16 | /** 17 | * setNull operations. 18 | * 19 | * @return key is index, value is {@link java.sql.Types} (int). 20 | */ 21 | Map getSetNullParamsByIndex(); 22 | 23 | /** 24 | * Keys of parameters. 25 | * 26 | * @return Integer keys. 27 | */ 28 | List getParamIndexes(); 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/net/ttddyy/dsproxy/asserts/ParameterByNameHolder.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts; 2 | 3 | import java.util.List; 4 | import java.util.Map; 5 | 6 | /** 7 | * Represent an execution that hold parameter by name. 8 | * 9 | * @author Tadaya Tsuyukubo 10 | * @since 1.0 11 | */ 12 | public interface ParameterByNameHolder extends ParameterHolder { 13 | 14 | Map getSetParamsByName(); 15 | 16 | Map getSetNullParamsByName(); 17 | 18 | /** 19 | * Keys of parameters. 20 | * Includes both set_param and set_null parameters. 21 | * 22 | * @return String keys. 23 | */ 24 | List getParamNames(); 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/net/ttddyy/dsproxy/asserts/ParameterHolder.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts; 2 | 3 | import java.util.SortedSet; 4 | 5 | /** 6 | * Represent execution that hold parameters. 7 | * 8 | * @author Tadaya Tsuyukubo 9 | * @since 1.0 10 | */ 11 | public interface ParameterHolder { 12 | 13 | SortedSet getAllParameters(); 14 | 15 | SortedSet getSetParams(); 16 | 17 | SortedSet getSetNullParams(); 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/net/ttddyy/dsproxy/asserts/ParameterKeyValue.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts; 2 | 3 | import net.ttddyy.dsproxy.proxy.ParameterKey; 4 | 5 | /** 6 | * @author Tadaya Tsuyukubo 7 | * @since 1.0 8 | */ 9 | public class ParameterKeyValue implements Comparable { 10 | 11 | public enum OperationType { 12 | SET_PARAM, SET_NULL, REGISTER_OUT 13 | } 14 | 15 | private ParameterKey key; 16 | private Object value; 17 | private String displayValue; 18 | private OperationType type; 19 | 20 | public ParameterKeyValue(int indexKey, Object value, String displayValue, OperationType type) { 21 | this(new ParameterKey(indexKey), value, displayValue, type); 22 | } 23 | 24 | public ParameterKeyValue(String nameKey, Object value, String displayValue, OperationType type) { 25 | this(new ParameterKey(nameKey), value, displayValue, type); 26 | } 27 | 28 | public ParameterKeyValue(ParameterKey key, Object value, String displayValue, OperationType type) { 29 | this.key = key; 30 | this.value = value; 31 | this.displayValue = displayValue; 32 | this.type = type; 33 | } 34 | 35 | public boolean isSetParam() { 36 | return this.type == OperationType.SET_PARAM; 37 | } 38 | 39 | public boolean isSetNull() { 40 | return this.type == OperationType.SET_NULL; 41 | } 42 | 43 | public boolean isRegisterOut() { 44 | return this.type == OperationType.REGISTER_OUT; 45 | } 46 | 47 | public ParameterKey getKey() { 48 | return this.key; 49 | } 50 | 51 | public void setKey(ParameterKey key) { 52 | this.key = key; 53 | } 54 | 55 | public Object getValue() { 56 | return this.value; 57 | } 58 | 59 | public void setValue(Object value) { 60 | this.value = value; 61 | } 62 | 63 | public String getDisplayValue() { 64 | return this.displayValue; 65 | } 66 | 67 | public void setDisplayValue(String displayValue) { 68 | this.displayValue = displayValue; 69 | } 70 | 71 | public OperationType getType() { 72 | return this.type; 73 | } 74 | 75 | public void setType(OperationType type) { 76 | this.type = type; 77 | } 78 | 79 | @Override 80 | public int compareTo(ParameterKeyValue o) { 81 | int byKey = this.key.compareTo(o.key); //use key for ordering 82 | if (byKey != 0) { 83 | return byKey; 84 | } 85 | return this.value == o.value ? 0 : 1; 86 | } 87 | 88 | } 89 | -------------------------------------------------------------------------------- /src/main/java/net/ttddyy/dsproxy/asserts/ParameterKeyValueUtils.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts; 2 | 3 | import net.ttddyy.dsproxy.listener.logging.RegisterOutParameterValueConverter; 4 | import net.ttddyy.dsproxy.listener.logging.SetNullParameterValueConverter; 5 | import net.ttddyy.dsproxy.proxy.ParameterKey; 6 | 7 | import java.util.Arrays; 8 | import java.util.LinkedHashMap; 9 | import java.util.Map; 10 | import java.util.SortedSet; 11 | import java.util.TreeSet; 12 | 13 | /** 14 | * @author Tadaya Tsuyukubo 15 | * @since 1.0 16 | */ 17 | public class ParameterKeyValueUtils { 18 | 19 | private static SetNullParameterValueConverter setNullValueConverter = new SetNullParameterValueConverter(); 20 | private static RegisterOutParameterValueConverter registerOutParameterValueConverter = new RegisterOutParameterValueConverter(); 21 | 22 | public static ParameterKeyValue createSetParam(int index, Object value) { 23 | String displayValue = value == null ? null : value.toString(); 24 | return new ParameterKeyValue(index, value, displayValue, ParameterKeyValue.OperationType.SET_PARAM); 25 | } 26 | 27 | public static ParameterKeyValue createSetParam(String name, Object value) { 28 | String displayValue = value == null ? null : value.toString(); 29 | return new ParameterKeyValue(name, value, displayValue, ParameterKeyValue.OperationType.SET_PARAM); 30 | } 31 | 32 | public static ParameterKeyValue createSetParam(ParameterKey key, Object value) { 33 | String displayValue = value == null ? null : value.toString(); 34 | return new ParameterKeyValue(key, value, displayValue, ParameterKeyValue.OperationType.SET_PARAM); 35 | } 36 | 37 | public static ParameterKeyValue createSetNull(int index, int sqlType) { 38 | String displayValue = setNullValueConverter.getDisplayValue(sqlType); 39 | return new ParameterKeyValue(index, sqlType, displayValue, ParameterKeyValue.OperationType.SET_NULL); 40 | } 41 | 42 | public static ParameterKeyValue createSetNull(String name, int sqlType) { 43 | String displayValue = setNullValueConverter.getDisplayValue(sqlType); 44 | return new ParameterKeyValue(name, sqlType, displayValue, ParameterKeyValue.OperationType.SET_NULL); 45 | } 46 | 47 | public static ParameterKeyValue createSetNull(ParameterKey key, int sqlType) { 48 | String displayValue = setNullValueConverter.getDisplayValue(sqlType); 49 | return new ParameterKeyValue(key, sqlType, displayValue, ParameterKeyValue.OperationType.SET_NULL); 50 | } 51 | 52 | public static ParameterKeyValue createRegisterOut(int index, Object value) { 53 | String displayValue = registerOutParameterValueConverter.getDisplayValue(value); 54 | return new ParameterKeyValue(index, value, displayValue, ParameterKeyValue.OperationType.REGISTER_OUT); 55 | } 56 | 57 | public static ParameterKeyValue createRegisterOut(String name, Object value) { 58 | String displayValue = registerOutParameterValueConverter.getDisplayValue(value); 59 | return new ParameterKeyValue(name, value, displayValue, ParameterKeyValue.OperationType.REGISTER_OUT); 60 | } 61 | 62 | public static ParameterKeyValue createRegisterOut(ParameterKey key, Object value) { 63 | String displayValue = registerOutParameterValueConverter.getDisplayValue(value); 64 | return new ParameterKeyValue(key, value, displayValue, ParameterKeyValue.OperationType.REGISTER_OUT); 65 | } 66 | 67 | public static SortedSet filterBy(SortedSet parameters, ParameterKeyValue.OperationType... operationTypes) { 68 | SortedSet result = new TreeSet<>(); 69 | for (ParameterKeyValue keyValue : parameters) { 70 | if (Arrays.asList(operationTypes).contains(keyValue.getType())) { 71 | result.add(keyValue); 72 | } 73 | } 74 | return result; 75 | } 76 | 77 | public static SortedSet filterByKeyType(SortedSet parameters, ParameterKey.ParameterKeyType keyType) { 78 | SortedSet result = new TreeSet<>(); 79 | for (ParameterKeyValue keyValue : parameters) { 80 | if (keyValue.getKey().getType() == keyType) { 81 | result.add(keyValue); 82 | } 83 | } 84 | return result; 85 | } 86 | 87 | public static SortedSet toParamKeys(SortedSet parameters) { 88 | SortedSet result = new TreeSet<>(); 89 | for (ParameterKeyValue keyValue : parameters) { 90 | result.add(keyValue.getKey()); 91 | } 92 | return result; 93 | } 94 | 95 | @SuppressWarnings("unchecked") 96 | public static Map toKeyValueMap(SortedSet keyValues) { 97 | Map result = new LinkedHashMap<>(); 98 | for (ParameterKeyValue keyValue : keyValues) { 99 | result.put(keyValue.getKey(), (T) keyValue.getValue()); 100 | } 101 | return result; 102 | } 103 | 104 | @SuppressWarnings("unchecked") 105 | public static Map toKeyIndexMap(SortedSet keyValues) { 106 | Map result = new LinkedHashMap<>(); 107 | for (ParameterKeyValue keyValue : keyValues) { 108 | result.put(keyValue.getKey().getIndex(), (T) keyValue.getValue()); 109 | } 110 | return result; 111 | } 112 | 113 | @SuppressWarnings("unchecked") 114 | public static Map toKeyNameMap(SortedSet keyValues) { 115 | Map result = new LinkedHashMap<>(); 116 | for (ParameterKeyValue keyValue : keyValues) { 117 | result.put(keyValue.getKey().getName(), (T) keyValue.getValue()); 118 | } 119 | return result; 120 | } 121 | 122 | public static Map toParamKeyMap(SortedSet keyValues) { 123 | Map result = new LinkedHashMap<>(); 124 | for (ParameterKeyValue keyValue : keyValues) { 125 | result.put(keyValue.getKey(), keyValue); 126 | } 127 | return result; 128 | } 129 | 130 | } 131 | -------------------------------------------------------------------------------- /src/main/java/net/ttddyy/dsproxy/asserts/PreparedBatchExecution.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * Represent a single batch execution of {@link java.sql.PreparedStatement}. 8 | * 9 | * @author Tadaya Tsuyukubo 10 | * @since 1.0 11 | */ 12 | public class PreparedBatchExecution extends BaseQueryExecution implements QueryHolder, BatchParameterHolder, BatchExecution { 13 | 14 | private String query; 15 | private List batchExecutionEntries = new ArrayList<>(); 16 | 17 | @Override 18 | public boolean isBatch() { 19 | return true; 20 | } 21 | 22 | public void setQuery(String query) { 23 | this.query = query; 24 | } 25 | 26 | @Override 27 | public String getQuery() { 28 | return this.query; 29 | } 30 | 31 | @Override 32 | public List getBatchExecutionEntries() { 33 | return this.batchExecutionEntries; 34 | } 35 | 36 | public boolean addBatchExecutionEntry(PreparedBatchExecutionEntry entry) { 37 | return this.batchExecutionEntries.add(entry); 38 | } 39 | 40 | @SuppressWarnings("unchecked") 41 | public List getPrepareds() { 42 | 43 | return (List) (List) this.batchExecutionEntries; 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/net/ttddyy/dsproxy/asserts/PreparedBatchExecutionEntry.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts; 2 | 3 | import net.ttddyy.dsproxy.proxy.ParameterKey; 4 | 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | import java.util.Map; 8 | import java.util.SortedSet; 9 | import java.util.TreeSet; 10 | 11 | import static net.ttddyy.dsproxy.asserts.ParameterKeyValueUtils.filterBy; 12 | import static net.ttddyy.dsproxy.asserts.ParameterKeyValueUtils.filterByKeyType; 13 | import static net.ttddyy.dsproxy.asserts.ParameterKeyValueUtils.toKeyIndexMap; 14 | 15 | /** 16 | * Represent batch entry of {@link java.sql.PreparedStatement}. 17 | * 18 | * @author Tadaya Tsuyukubo 19 | * @since 1.0 20 | */ 21 | public class PreparedBatchExecutionEntry implements BatchExecutionEntry, ParameterByIndexHolder { 22 | 23 | private SortedSet parameters = new TreeSet<>(); 24 | 25 | @Override 26 | public SortedSet getAllParameters() { 27 | return this.parameters; 28 | } 29 | 30 | @Override 31 | public SortedSet getSetParams() { 32 | return filterBy(this.parameters, ParameterKeyValue.OperationType.SET_PARAM); 33 | } 34 | 35 | @Override 36 | public SortedSet getSetNullParams() { 37 | return filterBy(this.parameters, ParameterKeyValue.OperationType.SET_NULL); 38 | } 39 | 40 | 41 | @Override 42 | public Map getSetParamsByIndex() { 43 | return toKeyIndexMap(filterByKeyType(getSetParams(), ParameterKey.ParameterKeyType.BY_INDEX)); 44 | } 45 | 46 | @Override 47 | public Map getSetNullParamsByIndex() { 48 | return toKeyIndexMap(filterByKeyType(getSetNullParams(), ParameterKey.ParameterKeyType.BY_INDEX)); 49 | } 50 | 51 | @Override 52 | public List getParamIndexes() { 53 | List indexes = new ArrayList<>(); 54 | indexes.addAll(getSetParamsByIndex().keySet()); 55 | indexes.addAll(getSetNullParamsByIndex().keySet()); 56 | return indexes; 57 | } 58 | 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/net/ttddyy/dsproxy/asserts/PreparedExecution.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts; 2 | 3 | import net.ttddyy.dsproxy.proxy.ParameterKey; 4 | 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | import java.util.Map; 8 | import java.util.SortedSet; 9 | import java.util.TreeSet; 10 | 11 | import static net.ttddyy.dsproxy.asserts.ParameterKeyValueUtils.filterBy; 12 | import static net.ttddyy.dsproxy.asserts.ParameterKeyValueUtils.filterByKeyType; 13 | import static net.ttddyy.dsproxy.asserts.ParameterKeyValueUtils.toKeyIndexMap; 14 | 15 | /** 16 | * Represent a single execution of {@link java.sql.PreparedStatement}. 17 | * 18 | * @author Tadaya Tsuyukubo 19 | * @since 1.0 20 | */ 21 | public class PreparedExecution extends BaseQueryExecution implements QueryHolder, ParameterByIndexHolder { 22 | 23 | private String query; 24 | private SortedSet parameters = new TreeSet<>(); 25 | 26 | @Override 27 | public boolean isBatch() { 28 | return false; 29 | } 30 | 31 | @Override 32 | public String getQuery() { 33 | return this.query; 34 | } 35 | 36 | public void setQuery(String query) { 37 | this.query = query; 38 | } 39 | 40 | @Override 41 | public SortedSet getAllParameters() { 42 | return this.parameters; 43 | } 44 | 45 | @Override 46 | public SortedSet getSetParams() { 47 | return filterBy(this.parameters, ParameterKeyValue.OperationType.SET_PARAM); 48 | } 49 | 50 | @Override 51 | public SortedSet getSetNullParams() { 52 | return filterBy(this.parameters, ParameterKeyValue.OperationType.SET_NULL); 53 | } 54 | 55 | @Override 56 | public Map getSetParamsByIndex() { 57 | return toKeyIndexMap(filterByKeyType(getSetParams(), ParameterKey.ParameterKeyType.BY_INDEX)); 58 | } 59 | 60 | @Override 61 | public Map getSetNullParamsByIndex() { 62 | return toKeyIndexMap(filterByKeyType(getSetNullParams(), ParameterKey.ParameterKeyType.BY_INDEX)); 63 | } 64 | 65 | @Override 66 | public List getParamIndexes() { 67 | List indexes = new ArrayList<>(); 68 | indexes.addAll(getSetParamsByIndex().keySet()); 69 | indexes.addAll(getSetNullParamsByIndex().keySet()); 70 | return indexes; 71 | } 72 | 73 | } 74 | -------------------------------------------------------------------------------- /src/main/java/net/ttddyy/dsproxy/asserts/ProxyTestDataSource.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts; 2 | 3 | import net.ttddyy.dsproxy.support.ProxyDataSource; 4 | 5 | import javax.sql.DataSource; 6 | import java.util.ArrayList; 7 | import java.util.List; 8 | 9 | /** 10 | * @author Tadaya Tsuyukubo 11 | * @since 1.0 12 | */ 13 | public class ProxyTestDataSource extends ProxyDataSource { 14 | 15 | private QueryExecutionFactoryListener queryExecutionFactoryListener = new QueryExecutionFactoryListener(); 16 | 17 | 18 | public ProxyTestDataSource() { 19 | initialize(); 20 | } 21 | 22 | public ProxyTestDataSource(DataSource dataSource) { 23 | super(dataSource); 24 | initialize(); 25 | } 26 | 27 | private void initialize() { 28 | this.getProxyConfig().getQueryListener().addListener(this.queryExecutionFactoryListener); 29 | } 30 | 31 | public void reset() { 32 | this.queryExecutionFactoryListener.reset(); 33 | } 34 | 35 | public List getStatements() { 36 | return getQueryExecutionsFilteredBy(StatementExecution.class); 37 | } 38 | 39 | public StatementExecution getFirstStatement() { 40 | return getFirstQueryExecution(StatementExecution.class); 41 | } 42 | 43 | public StatementExecution getLastStatement() { 44 | return getLastQueryExecution(StatementExecution.class); 45 | } 46 | 47 | public List getBatchStatements() { 48 | return getQueryExecutionsFilteredBy(StatementBatchExecution.class); 49 | } 50 | 51 | public StatementBatchExecution getFirstBatchStatement() { 52 | return getFirstQueryExecution(StatementBatchExecution.class); 53 | } 54 | 55 | public StatementBatchExecution getLastBatchStatement() { 56 | return getLastQueryExecution(StatementBatchExecution.class); 57 | } 58 | 59 | public List getPrepareds() { 60 | return getQueryExecutionsFilteredBy(PreparedExecution.class); 61 | } 62 | 63 | public PreparedExecution getFirstPrepared() { 64 | return getFirstQueryExecution(PreparedExecution.class); 65 | } 66 | 67 | public PreparedExecution getLastPrepared() { 68 | return getLastQueryExecution(PreparedExecution.class); 69 | } 70 | 71 | public List getBatchPrepareds() { 72 | return getQueryExecutionsFilteredBy(PreparedBatchExecution.class); 73 | } 74 | 75 | public PreparedBatchExecution getFirstBatchPrepared() { 76 | return getFirstQueryExecution(PreparedBatchExecution.class); 77 | } 78 | 79 | public PreparedBatchExecution getLastBatchPrepared() { 80 | return getLastQueryExecution(PreparedBatchExecution.class); 81 | } 82 | 83 | public List getCallables() { 84 | return getQueryExecutionsFilteredBy(CallableExecution.class); 85 | } 86 | 87 | public CallableExecution getFirstCallable() { 88 | return getFirstQueryExecution(CallableExecution.class); 89 | } 90 | 91 | public CallableExecution getLastCallable() { 92 | return getLastQueryExecution(CallableExecution.class); 93 | } 94 | 95 | public List getBatchCallables() { 96 | return getQueryExecutionsFilteredBy(CallableBatchExecution.class); 97 | } 98 | 99 | public CallableBatchExecution getFirstBatchCallable() { 100 | return getFirstQueryExecution(CallableBatchExecution.class); 101 | } 102 | 103 | public CallableBatchExecution getLastBatchCallable() { 104 | return getLastQueryExecution(CallableBatchExecution.class); 105 | } 106 | 107 | 108 | @SuppressWarnings("unchecked") 109 | private List getQueryExecutionsFilteredBy(Class classToFilter) { 110 | List result = new ArrayList<>(); 111 | for (QueryExecution queryExecution : getQueryExecutions()) { 112 | if (classToFilter.isAssignableFrom(queryExecution.getClass())) { 113 | result.add((T) queryExecution); 114 | } 115 | } 116 | return result; 117 | } 118 | 119 | private T getFirstQueryExecution(Class classToFilter) { 120 | List filtered = getQueryExecutionsFilteredBy(classToFilter); 121 | if (filtered.isEmpty()) { 122 | return null; 123 | } 124 | return filtered.get(0); 125 | } 126 | 127 | private T getLastQueryExecution(Class classToFilter) { 128 | List filtered = getQueryExecutionsFilteredBy(classToFilter); 129 | if (filtered.isEmpty()) { 130 | return null; 131 | } 132 | return filtered.get(filtered.size() - 1); 133 | } 134 | 135 | public List getQueryExecutions() { 136 | return this.queryExecutionFactoryListener.getQueryExecutions(); 137 | } 138 | 139 | public QueryExecutionFactoryListener getQueryExecutionFactoryListener() { 140 | return this.queryExecutionFactoryListener; 141 | } 142 | } 143 | -------------------------------------------------------------------------------- /src/main/java/net/ttddyy/dsproxy/asserts/QueriesHolder.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts; 2 | 3 | import java.util.List; 4 | 5 | /** 6 | * Represent an execution that hold multiple queries. 7 | * 8 | * @author Tadaya Tsuyukubo 9 | * @since 1.0 10 | */ 11 | public interface QueriesHolder { 12 | 13 | List getQueries(); 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/net/ttddyy/dsproxy/asserts/QueryExecution.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts; 2 | 3 | /** 4 | * Represent single query execution. 5 | * 6 | * @author Tadaya Tsuyukubo 7 | * @since 1.0 8 | */ 9 | public interface QueryExecution { 10 | 11 | boolean isSuccess(); 12 | 13 | boolean isBatch(); 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/net/ttddyy/dsproxy/asserts/QueryExtractor.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts; 2 | 3 | import java.util.List; 4 | 5 | /** 6 | * Retrieve queries from {@link QueryExecution}. 7 | * 8 | * @author Tadaya Tsuyukubo 9 | * @since 1.0 10 | */ 11 | public interface QueryExtractor { 12 | 13 | List getQueries(QueryExecution queryExecution); 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/net/ttddyy/dsproxy/asserts/QueryHolder.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts; 2 | 3 | /** 4 | * Interface to represent an execution that hold a single query. 5 | * 6 | * @author Tadaya Tsuyukubo 7 | * @since 1.0 8 | */ 9 | public interface QueryHolder { 10 | 11 | String getQuery(); 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/net/ttddyy/dsproxy/asserts/StatementBatchExecution.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * Represent single batch execution of {@link java.sql.Statement}. 8 | * 9 | * @author Tadaya Tsuyukubo 10 | * @since 1.0 11 | */ 12 | public class StatementBatchExecution extends BaseQueryExecution implements QueriesHolder, BatchExecution { 13 | 14 | private List queries = new ArrayList<>(); 15 | 16 | @Override 17 | public boolean isBatch() { 18 | return true; 19 | } 20 | 21 | @Override 22 | public List getQueries() { 23 | return this.queries; 24 | } 25 | 26 | public void setQueries(List queries) { 27 | this.queries = queries; 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/net/ttddyy/dsproxy/asserts/StatementExecution.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts; 2 | 3 | /** 4 | * Represent single execution of {@link java.sql.Statement}. 5 | * 6 | * @author Tadaya Tsuyukubo 7 | * @since 1.0 8 | */ 9 | public class StatementExecution extends BaseQueryExecution implements QueryHolder { 10 | 11 | private String query; 12 | 13 | @Override 14 | public boolean isBatch() { 15 | return false; 16 | } 17 | 18 | @Override 19 | public String getQuery() { 20 | return this.query; 21 | } 22 | 23 | public void setQuery(String query) { 24 | this.query = query; 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/net/ttddyy/dsproxy/asserts/assertj/AbstractExecutionAssert.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts.assertj; 2 | 3 | import net.ttddyy.dsproxy.asserts.QueryExecution; 4 | import org.assertj.core.api.AbstractAssert; 5 | 6 | /** 7 | * Shared asserts methods. 8 | * 9 | * @author Tadaya Tsuyukubo 10 | * @see QueryExecutionAssert 11 | * @see StatementExecutionAssert 12 | * @see StatementBatchExecutionAssert 13 | * @see PreparedExecutionAssert 14 | * @see PreparedBatchExecutionAssert 15 | * @see CallableExecutionAssert 16 | * @see CallableBatchExecutionAssert 17 | * @since 1.0 18 | */ 19 | public abstract class AbstractExecutionAssert, A extends QueryExecution> extends AbstractAssert { 20 | public AbstractExecutionAssert(A actual, Class selfType) { 21 | super(actual, selfType); 22 | } 23 | 24 | protected void isExecutionSuccess() { 25 | if (!this.actual.isSuccess()) { 26 | failWithMessage("%nExpecting: <%s> but was: <%s>%n", "Successful execution", "Failure execution"); 27 | } 28 | } 29 | 30 | protected void isExecutionFailure() { 31 | if (this.actual.isSuccess()) { 32 | failWithMessage("%nExpecting: <%s> but was: <%s>%n", "Failure execution", "Successful execution"); 33 | } 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/net/ttddyy/dsproxy/asserts/assertj/CallableBatchExecutionAssert.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts.assertj; 2 | 3 | import net.ttddyy.dsproxy.asserts.CallableBatchExecution; 4 | import net.ttddyy.dsproxy.asserts.CallableBatchExecutionEntry; 5 | import net.ttddyy.dsproxy.asserts.assertj.data.ExecutionParameters; 6 | import net.ttddyy.dsproxy.asserts.assertj.helper.BatchExecutionEntryAsserts; 7 | import net.ttddyy.dsproxy.asserts.assertj.helper.ExecutionParameterAsserts; 8 | import org.assertj.core.api.AbstractCharSequenceAssert; 9 | import org.assertj.core.api.Assertions; 10 | 11 | /** 12 | * @author Tadaya Tsuyukubo 13 | * @since 1.0 14 | */ 15 | // TODO: should this extend AbstractAssert?? 16 | public class CallableBatchExecutionAssert extends AbstractExecutionAssert { 17 | 18 | private BatchExecutionEntryAsserts batchAssert = new BatchExecutionEntryAsserts(this.info); 19 | private ExecutionParameterAsserts parameterAssert = new ExecutionParameterAsserts(this.info); 20 | 21 | public CallableBatchExecutionAssert(CallableBatchExecution actual) { 22 | super(actual, CallableBatchExecutionAssert.class); 23 | } 24 | 25 | public CallableBatchExecutionAssert isSuccess() { 26 | isExecutionSuccess(); 27 | return this; 28 | } 29 | 30 | public CallableBatchExecutionAssert isFailure() { 31 | isExecutionFailure(); 32 | return this; 33 | } 34 | 35 | public CallableBatchExecutionAssert hasBatchSize(int batchSize) { 36 | this.batchAssert.assertBatchSize(this.actual, batchSize, "callable"); 37 | return this; 38 | } 39 | 40 | 41 | public CallableBatchExecutionAssert batch(int batchIndex, ExecutionParameters params) { 42 | 43 | this.batchAssert.assertBatchExecutionEntry(this.actual, batchIndex, CallableBatchExecutionEntry.class); 44 | 45 | // entry is validated to be the one for callable 46 | CallableBatchExecutionEntry batchEntry = (CallableBatchExecutionEntry) this.actual.getBatchExecutionEntries().get(batchIndex); 47 | this.parameterAssert.assertParameterKeys(batchEntry, params, true); 48 | 49 | 50 | if (ExecutionParameters.ExecutionParametersType.CONTAINS_KEYS_ONLY == params.getType()) { 51 | return this; // only check keys 52 | } 53 | 54 | // validate key-value pairs 55 | this.parameterAssert.assertExecutionParameters(batchEntry, params); 56 | 57 | return this; 58 | } 59 | 60 | public AbstractCharSequenceAssert query() { 61 | return Assertions.assertThat(this.actual.getQuery()); 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/net/ttddyy/dsproxy/asserts/assertj/CallableExecutionAssert.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts.assertj; 2 | 3 | import net.ttddyy.dsproxy.asserts.CallableExecution; 4 | import net.ttddyy.dsproxy.asserts.assertj.data.ExecutionParameter; 5 | import net.ttddyy.dsproxy.asserts.assertj.data.ExecutionParameters; 6 | import net.ttddyy.dsproxy.asserts.assertj.helper.ExecutionParameterAsserts; 7 | import org.assertj.core.api.AbstractCharSequenceAssert; 8 | import org.assertj.core.api.Assertions; 9 | 10 | import java.sql.SQLType; 11 | 12 | /** 13 | * @author Tadaya Tsuyukubo 14 | * @since 1.0 15 | */ 16 | public class CallableExecutionAssert extends AbstractExecutionAssert { 17 | 18 | private ExecutionParameterAsserts parameterAsserts = new ExecutionParameterAsserts(this.info); 19 | 20 | public CallableExecutionAssert(CallableExecution actual) { 21 | super(actual, CallableExecutionAssert.class); 22 | } 23 | 24 | public CallableExecutionAssert isSuccess() { 25 | this.isExecutionSuccess(); 26 | return this; 27 | } 28 | 29 | public CallableExecutionAssert isFailure() { 30 | this.isExecutionFailure(); 31 | return this; 32 | } 33 | 34 | public CallableExecutionAssert containsParam(int paramIndex, Object value) { 35 | containsParams(ExecutionParameter.param(paramIndex, value)); 36 | return this; 37 | } 38 | 39 | public CallableExecutionAssert containsParam(String paramName, Object value) { 40 | containsParams(ExecutionParameter.param(paramName, value)); 41 | return this; 42 | } 43 | 44 | public CallableExecutionAssert containsNullParam(int index, int sqlType) { 45 | containsParams(ExecutionParameter.nullParam(index, sqlType)); 46 | return this; 47 | } 48 | 49 | public CallableExecutionAssert containsNullParam(int index) { 50 | containsParams(ExecutionParameter.nullParam(index)); 51 | return this; 52 | } 53 | 54 | public CallableExecutionAssert containsNullParam(String name, int sqlType) { 55 | containsParams(ExecutionParameter.nullParam(name, sqlType)); 56 | return this; 57 | } 58 | 59 | public CallableExecutionAssert containsNullParam(String name) { 60 | containsParams(ExecutionParameter.nullParam(name)); 61 | return this; 62 | } 63 | 64 | public CallableExecutionAssert containsOutParam(int paramIndex, int sqlType) { 65 | containsParams(ExecutionParameter.outParam(paramIndex, sqlType)); 66 | return this; 67 | } 68 | 69 | public CallableExecutionAssert containsOutParam(int paramIndex, SQLType sqlType) { 70 | containsParams(ExecutionParameter.outParam(paramIndex, sqlType)); 71 | return this; 72 | } 73 | 74 | public CallableExecutionAssert containsOutParam(String paramName, int sqlType) { 75 | containsParams(ExecutionParameter.outParam(paramName, sqlType)); 76 | return this; 77 | } 78 | 79 | public CallableExecutionAssert containsOutParam(String paramName, SQLType sqlType) { 80 | containsParams(ExecutionParameter.outParam(paramName, sqlType)); 81 | return this; 82 | } 83 | 84 | 85 | public CallableExecutionAssert containsParams(ExecutionParameter... params) { 86 | ExecutionParameters executionParameters = ExecutionParameters.containsParams(params); 87 | this.parameterAsserts.assertParameterKeys(this.actual, executionParameters, true); 88 | this.parameterAsserts.assertExecutionParameters(this.actual, executionParameters); 89 | return this; 90 | } 91 | 92 | public CallableExecutionAssert containsParamsExactly(ExecutionParameter... params) { 93 | ExecutionParameters executionParameters = ExecutionParameters.containsParamsExactly(params); 94 | this.parameterAsserts.assertParameterKeys(this.actual, executionParameters, true); 95 | this.parameterAsserts.assertExecutionParameters(this.actual, executionParameters); 96 | return this; 97 | } 98 | 99 | public CallableExecutionAssert containsParamKey(Object paramKey) { 100 | containsParamKeys(paramKey); 101 | return this; 102 | } 103 | 104 | public CallableExecutionAssert containsParamKeys(Object... paramKeys) { 105 | ExecutionParameters executionParameters = ExecutionParameters.containsParamKeys(paramKeys); 106 | this.parameterAsserts.assertParameterKeys(this.actual, executionParameters, true); 107 | return this; 108 | } 109 | 110 | public CallableExecutionAssert containsParamIndex(int paramIndex) { 111 | containsParamIndexes(paramIndex); 112 | return this; 113 | } 114 | 115 | public CallableExecutionAssert containsParamIndexes(int... paramIndexes) { 116 | ExecutionParameters executionParameters = ExecutionParameters.containsParamIndexes(paramIndexes); 117 | this.parameterAsserts.assertParameterKeys(this.actual, executionParameters, true); 118 | return this; 119 | } 120 | 121 | public CallableExecutionAssert containsParamName(String paramName) { 122 | containsParamNames(paramName); 123 | return this; 124 | } 125 | 126 | public CallableExecutionAssert containsParamNames(String... paramNames) { 127 | ExecutionParameters executionParameters = ExecutionParameters.containsParamNames(paramNames); 128 | this.parameterAsserts.assertParameterKeys(this.actual, executionParameters, true); 129 | return this; 130 | } 131 | 132 | public AbstractCharSequenceAssert query() { 133 | return Assertions.assertThat(this.actual.getQuery()); 134 | } 135 | 136 | } 137 | -------------------------------------------------------------------------------- /src/main/java/net/ttddyy/dsproxy/asserts/assertj/DataSourceAssertAssertions.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts.assertj; 2 | 3 | import net.ttddyy.dsproxy.asserts.CallableBatchExecution; 4 | import net.ttddyy.dsproxy.asserts.CallableExecution; 5 | import net.ttddyy.dsproxy.asserts.PreparedBatchExecution; 6 | import net.ttddyy.dsproxy.asserts.PreparedExecution; 7 | import net.ttddyy.dsproxy.asserts.ProxyTestDataSource; 8 | import net.ttddyy.dsproxy.asserts.QueryExecution; 9 | import net.ttddyy.dsproxy.asserts.StatementBatchExecution; 10 | import net.ttddyy.dsproxy.asserts.StatementExecution; 11 | import net.ttddyy.dsproxy.asserts.assertj.data.ExecutionParameter; 12 | import net.ttddyy.dsproxy.asserts.assertj.data.ExecutionParameters; 13 | 14 | import java.sql.SQLType; 15 | 16 | /** 17 | * Aggregated assertj assertions. 18 | * 19 | * @author Tadaya Tsuyukubo 20 | * @see ProxyTestDataSourceAssert 21 | * @see StatementExecutionAssert 22 | * @since 1.0 23 | */ 24 | public class DataSourceAssertAssertions { 25 | 26 | public static ProxyTestDataSourceAssert assertThat(ProxyTestDataSource actual) { 27 | return new ProxyTestDataSourceAssert(actual); 28 | } 29 | 30 | public static QueryExecutionAssert assertThat(QueryExecution actual) { 31 | return new QueryExecutionAssert(actual); 32 | } 33 | 34 | public static StatementExecutionAssert assertThat(StatementExecution actual) { 35 | return new StatementExecutionAssert(actual); 36 | } 37 | 38 | public static StatementBatchExecutionAssert assertThat(StatementBatchExecution actual) { 39 | return new StatementBatchExecutionAssert(actual); 40 | } 41 | 42 | public static PreparedExecutionAssert assertThat(PreparedExecution actual) { 43 | return new PreparedExecutionAssert(actual); 44 | } 45 | 46 | public static PreparedBatchExecutionAssert assertThat(PreparedBatchExecution actual) { 47 | return new PreparedBatchExecutionAssert(actual); 48 | } 49 | 50 | public static CallableExecutionAssert assertThat(CallableExecution actual) { 51 | return new CallableExecutionAssert(actual); 52 | } 53 | 54 | public static CallableBatchExecutionAssert assertThat(CallableBatchExecution actual) { 55 | return new CallableBatchExecutionAssert(actual); 56 | } 57 | 58 | // from ExecutionParameter 59 | 60 | public static ExecutionParameter param(int paramIndex, Object value) { 61 | return ExecutionParameter.param(paramIndex, value); 62 | } 63 | 64 | public static ExecutionParameter param(String paramName, Object value) { 65 | return ExecutionParameter.param(paramName, value); 66 | } 67 | 68 | public static ExecutionParameter nullParam(int index, int sqlType) { 69 | return ExecutionParameter.nullParam(index, sqlType); 70 | } 71 | 72 | public static ExecutionParameter nullParam(int index) { 73 | return ExecutionParameter.nullParam(index); 74 | } 75 | 76 | public static ExecutionParameter nullParam(String name, int sqlType) { 77 | return ExecutionParameter.nullParam(name, sqlType); 78 | } 79 | 80 | public static ExecutionParameter nullParam(String name) { 81 | return ExecutionParameter.nullParam(name); 82 | } 83 | 84 | public static ExecutionParameter outParam(int paramIndex, int sqlType) { 85 | return ExecutionParameter.outParam(paramIndex, sqlType); 86 | } 87 | 88 | public static ExecutionParameter outParam(int paramIndex, SQLType sqlType) { 89 | return ExecutionParameter.outParam(paramIndex, sqlType); 90 | } 91 | 92 | public static ExecutionParameter outParam(String paramName, int sqlType) { 93 | return ExecutionParameter.outParam(paramName, sqlType); 94 | } 95 | 96 | public static ExecutionParameter outParam(String paramName, SQLType sqlType) { 97 | return ExecutionParameter.outParam(paramName, sqlType); 98 | } 99 | 100 | // from ExecutionParameters 101 | 102 | public static ExecutionParameters containsParams(ExecutionParameter... params) { 103 | return ExecutionParameters.containsParams(params); 104 | } 105 | 106 | public static ExecutionParameters containsParamsExactly(ExecutionParameter... params) { 107 | return ExecutionParameters.containsParamsExactly(params); 108 | } 109 | 110 | public static ExecutionParameters containsParamKeys(Object... paramKeys) { 111 | return ExecutionParameters.containsParamKeys(paramKeys); 112 | } 113 | 114 | public static ExecutionParameters containsParamIndexes(int... paramIndexes) { 115 | return ExecutionParameters.containsParamIndexes(paramIndexes); 116 | } 117 | 118 | public static ExecutionParameters containsParamNames(String... paramNames) { 119 | return ExecutionParameters.containsParamNames(paramNames); 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /src/main/java/net/ttddyy/dsproxy/asserts/assertj/PreparedBatchExecutionAssert.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts.assertj; 2 | 3 | import net.ttddyy.dsproxy.asserts.PreparedBatchExecution; 4 | import net.ttddyy.dsproxy.asserts.PreparedBatchExecutionEntry; 5 | import net.ttddyy.dsproxy.asserts.assertj.data.ExecutionParameters; 6 | import net.ttddyy.dsproxy.asserts.assertj.helper.BatchExecutionEntryAsserts; 7 | import net.ttddyy.dsproxy.asserts.assertj.helper.ExecutionParameterAsserts; 8 | import org.assertj.core.api.AbstractCharSequenceAssert; 9 | import org.assertj.core.api.Assertions; 10 | 11 | /** 12 | * @author Tadaya Tsuyukubo 13 | * @since 1.0 14 | */ 15 | public class PreparedBatchExecutionAssert extends AbstractExecutionAssert { 16 | 17 | private BatchExecutionEntryAsserts batchAssert = new BatchExecutionEntryAsserts(this.info); 18 | private ExecutionParameterAsserts parameterAssert = new ExecutionParameterAsserts(this.info); 19 | 20 | public PreparedBatchExecutionAssert(PreparedBatchExecution actual) { 21 | super(actual, PreparedBatchExecutionAssert.class); 22 | } 23 | 24 | public PreparedBatchExecutionAssert isSuccess() { 25 | isExecutionSuccess(); 26 | return this; 27 | } 28 | 29 | public PreparedBatchExecutionAssert isFailure() { 30 | isExecutionFailure(); 31 | return this; 32 | } 33 | 34 | public PreparedBatchExecutionAssert hasBatchSize(int batchSize) { 35 | this.batchAssert.assertBatchSize(this.actual, batchSize, "prepared"); 36 | return this; 37 | } 38 | 39 | 40 | public PreparedBatchExecutionAssert batch(int batchIndex, ExecutionParameters params) { 41 | 42 | this.batchAssert.assertBatchExecutionEntry(this.actual, batchIndex, PreparedBatchExecutionEntry.class); 43 | 44 | // entry is validated to be the one for prepared 45 | PreparedBatchExecutionEntry batchEntry = (PreparedBatchExecutionEntry) this.actual.getBatchExecutionEntries().get(batchIndex); 46 | this.parameterAssert.assertParameterKeys(batchEntry, params, false); 47 | 48 | if (ExecutionParameters.ExecutionParametersType.CONTAINS_KEYS_ONLY == params.getType()) { 49 | return this; // only check keys 50 | } 51 | 52 | // validate key-value pairs 53 | this.parameterAssert.assertExecutionParameters(batchEntry, params); 54 | 55 | return this; 56 | } 57 | 58 | public AbstractCharSequenceAssert query() { 59 | return Assertions.assertThat(this.actual.getQuery()); 60 | } 61 | 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/net/ttddyy/dsproxy/asserts/assertj/QueryExecutionAssert.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts.assertj; 2 | 3 | import net.ttddyy.dsproxy.StatementType; 4 | import net.ttddyy.dsproxy.asserts.CallableBatchExecution; 5 | import net.ttddyy.dsproxy.asserts.CallableExecution; 6 | import net.ttddyy.dsproxy.asserts.PreparedBatchExecution; 7 | import net.ttddyy.dsproxy.asserts.PreparedExecution; 8 | import net.ttddyy.dsproxy.asserts.QueryExecution; 9 | import net.ttddyy.dsproxy.asserts.StatementBatchExecution; 10 | import net.ttddyy.dsproxy.asserts.StatementExecution; 11 | 12 | /** 13 | * @author Tadaya Tsuyukubo 14 | * @since 1.0 15 | */ 16 | public class QueryExecutionAssert extends AbstractExecutionAssert { 17 | 18 | public QueryExecutionAssert(QueryExecution actual) { 19 | super(actual, QueryExecutionAssert.class); 20 | } 21 | 22 | public QueryExecutionAssert isSuccess() { 23 | isExecutionSuccess(); 24 | return this; 25 | } 26 | 27 | public QueryExecutionAssert isFailure() { 28 | isExecutionFailure(); 29 | return this; 30 | } 31 | 32 | public QueryExecutionAssert isBatch() { 33 | if (!this.actual.isBatch()) { 34 | failWithMessage("%nExpecting: <%s> but was: <%s>%n", "Batch Execution", "Not Batch Execution"); 35 | } 36 | return this; 37 | } 38 | 39 | public QueryExecutionAssert isStatement() { 40 | boolean isStatement = this.actual instanceof StatementExecution; 41 | if (!isStatement) { 42 | String actualType = getStatementTypeMessage(this.actual); 43 | failWithMessage("%nExpecting: <%s> but was: <%s>%n", "STATEMENT", actualType); 44 | } 45 | return this; 46 | } 47 | 48 | public QueryExecutionAssert isBatchStatement() { 49 | boolean isBatchStatement = this.actual instanceof StatementBatchExecution; 50 | if (!isBatchStatement) { 51 | String actualType = getStatementTypeMessage(this.actual); 52 | failWithMessage("%nExpecting: <%s> but was: <%s>%n", "BATCH STATEMENT", actualType); 53 | } 54 | return this; 55 | } 56 | 57 | public QueryExecutionAssert isStatementOrBatchStatement() { 58 | boolean isStatement = this.actual instanceof StatementExecution; 59 | boolean isBatchStatement = this.actual instanceof StatementBatchExecution; 60 | 61 | if (!(isStatement || isBatchStatement)) { 62 | String actualType = getStatementTypeMessage(this.actual); 63 | failWithMessage("%nExpecting: <%s> but was: <%s>%n", "STATEMENT or BATCH STATEMENT", actualType); 64 | } 65 | return this; 66 | } 67 | 68 | public QueryExecutionAssert isPrepared() { 69 | boolean isPrepared = this.actual instanceof PreparedExecution; 70 | if (!isPrepared) { 71 | String actualType = getStatementTypeMessage(this.actual); 72 | failWithMessage("%nExpecting: <%s> but was: <%s>%n", "PREPARED", actualType); 73 | } 74 | return this; 75 | } 76 | 77 | public QueryExecutionAssert isBatchPrepared() { 78 | boolean isBatchPrepared = this.actual instanceof PreparedBatchExecution; 79 | if (!isBatchPrepared) { 80 | String actualType = getStatementTypeMessage(this.actual); 81 | failWithMessage("%nExpecting: <%s> but was: <%s>%n", "BATCH PREPARED", actualType); 82 | } 83 | return this; 84 | } 85 | 86 | public QueryExecutionAssert isPreparedOrBatchPrepared() { 87 | boolean isPrepared = this.actual instanceof PreparedExecution; 88 | boolean isBatchPrepared = this.actual instanceof PreparedBatchExecution; 89 | 90 | if (!(isPrepared || isBatchPrepared)) { 91 | String actualType = getStatementTypeMessage(this.actual); 92 | failWithMessage("%nExpecting: <%s> but was: <%s>%n", "PREPARED or BATCH PREPARED", actualType); 93 | } 94 | 95 | return this; 96 | } 97 | 98 | public QueryExecutionAssert isCallable() { 99 | boolean isCallable = this.actual instanceof CallableExecution; 100 | if (!isCallable) { 101 | String actualType = getStatementTypeMessage(this.actual); 102 | failWithMessage("%nExpecting: <%s> but was: <%s>%n", "CALLABLE", actualType); 103 | } 104 | return this; 105 | } 106 | 107 | public QueryExecutionAssert isBatchCallable() { 108 | boolean isBatchCallable = this.actual instanceof CallableBatchExecution; 109 | if (!isBatchCallable) { 110 | String actualType = getStatementTypeMessage(this.actual); 111 | failWithMessage("%nExpecting: <%s> but was: <%s>%n", "BATCH CALLABLE", actualType); 112 | } 113 | return this; 114 | } 115 | 116 | public QueryExecutionAssert isCallableOrBatchCallable() { 117 | boolean isCallable = this.actual instanceof CallableExecution; 118 | boolean isBatchCallable = this.actual instanceof CallableBatchExecution; 119 | if (!(isCallable || isBatchCallable)) { 120 | String actualType = getStatementTypeMessage(this.actual); 121 | failWithMessage("%nExpecting: <%s> but was: <%s>%n", "CALLABLE or BATCH CALLABLE", actualType); 122 | } 123 | return this; 124 | } 125 | 126 | private String getStatementTypeMessage(QueryExecution queryExecution) { 127 | boolean isBatch = queryExecution.isBatch(); 128 | StatementType type = getStatementType(queryExecution); 129 | return isBatch ? "BATCH " + type : type.toString(); 130 | } 131 | 132 | private StatementType getStatementType(QueryExecution queryExecution) { 133 | if (queryExecution instanceof StatementExecution || queryExecution instanceof StatementBatchExecution) { 134 | return StatementType.STATEMENT; 135 | } else if (queryExecution instanceof PreparedExecution || queryExecution instanceof PreparedBatchExecution) { 136 | return StatementType.PREPARED; 137 | } else if (queryExecution instanceof CallableExecution || queryExecution instanceof CallableBatchExecution) { 138 | return StatementType.CALLABLE; 139 | } 140 | throw new IllegalArgumentException(); 141 | } 142 | 143 | public StatementExecutionAssert asStatement() { 144 | return DataSourceAssertAssertions.assertThat((StatementExecution) this.actual); 145 | } 146 | 147 | public StatementBatchExecutionAssert asBatchStatement() { 148 | return DataSourceAssertAssertions.assertThat((StatementBatchExecution) this.actual); 149 | } 150 | 151 | public PreparedExecutionAssert asPrepared() { 152 | return DataSourceAssertAssertions.assertThat((PreparedExecution) this.actual); 153 | } 154 | 155 | public PreparedBatchExecutionAssert asBatchPrepared() { 156 | return DataSourceAssertAssertions.assertThat((PreparedBatchExecution) this.actual); 157 | } 158 | 159 | public CallableExecutionAssert asCallable() { 160 | return DataSourceAssertAssertions.assertThat((CallableExecution) this.actual); 161 | } 162 | 163 | public CallableBatchExecutionAssert asBatchCallable() { 164 | return DataSourceAssertAssertions.assertThat((CallableBatchExecution) this.actual); 165 | } 166 | 167 | 168 | } 169 | -------------------------------------------------------------------------------- /src/main/java/net/ttddyy/dsproxy/asserts/assertj/StatementBatchExecutionAssert.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts.assertj; 2 | 3 | import net.ttddyy.dsproxy.QueryType; 4 | import net.ttddyy.dsproxy.asserts.StatementBatchExecution; 5 | import net.ttddyy.dsproxy.listener.QueryUtils; 6 | import org.assertj.core.api.AbstractCharSequenceAssert; 7 | import org.assertj.core.api.AbstractListAssert; 8 | import org.assertj.core.api.Assertions; 9 | import org.assertj.core.api.ObjectAssert; 10 | import org.assertj.core.data.Index; 11 | 12 | import java.util.List; 13 | 14 | /** 15 | * @author Tadaya Tsuyukubo 16 | * @since 1.0 17 | */ 18 | // TODO: should this extend AbstractAssert?? 19 | public class StatementBatchExecutionAssert extends AbstractExecutionAssert { 20 | 21 | public StatementBatchExecutionAssert(StatementBatchExecution actual) { 22 | super(actual, StatementBatchExecutionAssert.class); 23 | } 24 | 25 | public StatementBatchExecutionAssert isSuccess() { 26 | isExecutionSuccess(); 27 | return this; 28 | } 29 | 30 | public StatementBatchExecutionAssert isFailure() { 31 | isExecutionFailure(); 32 | return this; 33 | } 34 | 35 | public StatementBatchExecutionAssert hasBatchSize(int batchSize) { 36 | int actualSize = this.actual.getQueries().size(); 37 | if (actualSize != batchSize) { 38 | failWithMessage("%nExpected batch size:<%s> but was:<%s> in batch statement executions%n", batchSize, actualSize); 39 | } 40 | return this; 41 | } 42 | 43 | public AbstractListAssert, String, ObjectAssert> queries() { 44 | return Assertions.assertThat(this.actual.getQueries()); 45 | } 46 | 47 | public AbstractCharSequenceAssert query(Index index) { 48 | return query(index.value); 49 | } 50 | 51 | public AbstractCharSequenceAssert query(int index) { 52 | String query = this.actual.getQueries().get(index); 53 | return Assertions.assertThat(query); 54 | } 55 | 56 | public StatementBatchExecutionAssert contains(QueryType queryType, Index index) { 57 | return contains(queryType, index.value); 58 | } 59 | 60 | public StatementBatchExecutionAssert contains(QueryType queryType, int index) { 61 | String query = this.actual.getQueries().get(index); 62 | 63 | QueryType actualType = QueryUtils.getQueryType(query); 64 | if (actualType != queryType) { 65 | failWithMessage("%nExpected query type:<%s> but was:<%s> at index:<%d>%n", queryType, actualType, index); 66 | } 67 | return this; 68 | } 69 | 70 | public StatementBatchExecutionAssert hasSelectCount(int count) { 71 | return hasQueryCount(QueryType.SELECT, count); 72 | } 73 | 74 | public StatementBatchExecutionAssert hasInsertCount(int count) { 75 | return hasQueryCount(QueryType.INSERT, count); 76 | } 77 | 78 | public StatementBatchExecutionAssert hasUpdateCount(int count) { 79 | return hasQueryCount(QueryType.UPDATE, count); 80 | } 81 | 82 | public StatementBatchExecutionAssert hasDeleteCount(int count) { 83 | return hasQueryCount(QueryType.DELETE, count); 84 | } 85 | 86 | public StatementBatchExecutionAssert hasOtherCount(int count) { 87 | return hasQueryCount(QueryType.OTHER, count); 88 | } 89 | 90 | public StatementBatchExecutionAssert hasQueryCount(QueryType queryType, int count) { 91 | 92 | int matchedCount = 0; 93 | int selectCount = 0; 94 | int insertCount = 0; 95 | int updateCount = 0; 96 | int deleteCount = 0; 97 | int otherCount = 0; 98 | for (String query : this.actual.getQueries()) { 99 | QueryType actualQueryType = QueryUtils.getQueryType(query); 100 | switch (actualQueryType) { 101 | case SELECT: 102 | selectCount++; 103 | break; 104 | case INSERT: 105 | insertCount++; 106 | break; 107 | case UPDATE: 108 | updateCount++; 109 | break; 110 | case DELETE: 111 | deleteCount++; 112 | break; 113 | case OTHER: 114 | otherCount++; 115 | break; 116 | } 117 | if (queryType.equals(actualQueryType)) { 118 | matchedCount++; 119 | } 120 | } 121 | if (matchedCount != count) { 122 | String summary = String.format("select=%d, insert=%d, update=%d, delete=%d, other=%d", 123 | selectCount, insertCount, updateCount, deleteCount, otherCount); 124 | failWithMessage("%nExpected %s count:<%d> but was:<%d> in:%n<%s>", queryType, count, matchedCount, summary); 125 | } 126 | 127 | return this; 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /src/main/java/net/ttddyy/dsproxy/asserts/assertj/StatementExecutionAssert.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts.assertj; 2 | 3 | import net.ttddyy.dsproxy.QueryType; 4 | import net.ttddyy.dsproxy.asserts.StatementExecution; 5 | import net.ttddyy.dsproxy.listener.QueryUtils; 6 | import org.assertj.core.api.AbstractCharSequenceAssert; 7 | import org.assertj.core.api.Assertions; 8 | 9 | /** 10 | * @author Tadaya Tsuyukubo 11 | * @since 1.0 12 | */ 13 | public class StatementExecutionAssert extends AbstractExecutionAssert { 14 | 15 | public StatementExecutionAssert(StatementExecution actual) { 16 | super(actual, StatementExecutionAssert.class); 17 | } 18 | 19 | public StatementExecutionAssert isSuccess() { 20 | isExecutionSuccess(); 21 | return this; 22 | } 23 | 24 | public StatementExecutionAssert isFailure() { 25 | isExecutionFailure(); 26 | return this; 27 | } 28 | 29 | public AbstractCharSequenceAssert query() { 30 | return Assertions.assertThat(this.actual.getQuery()); 31 | } 32 | 33 | public StatementExecutionAssert isSelect() { 34 | hasQueryType(QueryType.SELECT); 35 | return this; 36 | } 37 | 38 | public StatementExecutionAssert isInsert() { 39 | hasQueryType(QueryType.INSERT); 40 | return this; 41 | } 42 | 43 | public StatementExecutionAssert isUpdate() { 44 | hasQueryType(QueryType.UPDATE); 45 | return this; 46 | } 47 | 48 | public StatementExecutionAssert isDelete() { 49 | hasQueryType(QueryType.DELETE); 50 | return this; 51 | } 52 | 53 | public StatementExecutionAssert isOther() { 54 | hasQueryType(QueryType.OTHER); 55 | return this; 56 | } 57 | 58 | public StatementExecutionAssert hasQueryType(QueryType queryType) { 59 | String query = this.actual.getQuery(); 60 | QueryType actualType = QueryUtils.getQueryType(query); 61 | if (actualType != queryType) { 62 | failWithMessage("%nExpected query type:<%s> but was:<%s>%n", queryType, actualType); 63 | } 64 | return this; 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/net/ttddyy/dsproxy/asserts/assertj/data/ExecutionParameter.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts.assertj.data; 2 | 3 | import net.ttddyy.dsproxy.proxy.ParameterKey; 4 | 5 | import java.sql.SQLType; 6 | 7 | /** 8 | * @author Tadaya Tsuyukubo 9 | * @since 1.0 10 | */ 11 | public abstract class ExecutionParameter { 12 | 13 | /** 14 | * Only for param keys. Do not care whether it is from setParams, setNullParams, or registerOutParams. 15 | */ 16 | public static class ParamKeyOnlyExecution extends ExecutionParameter { 17 | public ParamKeyOnlyExecution(ParameterKey parameterKey) { 18 | super(parameterKey); 19 | } 20 | } 21 | 22 | /** 23 | * For setParam operations. 24 | */ 25 | public static class SetParamExecution extends ExecutionParameter { 26 | private Object value; 27 | 28 | public SetParamExecution(ParameterKey parameterKey, Object value) { 29 | super(parameterKey); 30 | this.value = value; 31 | } 32 | 33 | public Object getValue() { 34 | return value; 35 | } 36 | } 37 | 38 | /** 39 | * For setNull operations 40 | */ 41 | public static class SetNullParamExecution extends ExecutionParameter { 42 | private Integer sqlType; // null if do not check sqlType 43 | 44 | public SetNullParamExecution(ParameterKey parameterKey, Integer sqlType) { 45 | super(parameterKey); 46 | this.sqlType = sqlType; 47 | } 48 | 49 | public Integer getSqlType() { 50 | return this.sqlType; 51 | } 52 | } 53 | 54 | public static class RegisterOutParamExecutionWithIntType extends ExecutionParameter { 55 | private int sqlType; 56 | 57 | public RegisterOutParamExecutionWithIntType(ParameterKey parameterKey, int sqlType) { 58 | super(parameterKey); 59 | this.sqlType = sqlType; 60 | } 61 | 62 | public int getSqlType() { 63 | return this.sqlType; 64 | } 65 | } 66 | 67 | public static class RegisterOutParamExecutionWithSQLType extends ExecutionParameter { 68 | private SQLType sqlType; 69 | 70 | public RegisterOutParamExecutionWithSQLType(ParameterKey parameterKey, SQLType sqlType) { 71 | super(parameterKey); 72 | this.sqlType = sqlType; 73 | } 74 | 75 | public SQLType getSqlType() { 76 | return this.sqlType; 77 | } 78 | } 79 | 80 | public static ExecutionParameter param(int paramIndex, Object value) { 81 | return new SetParamExecution(new ParameterKey(paramIndex), value); 82 | } 83 | 84 | public static ExecutionParameter param(String paramName, Object value) { 85 | return new SetParamExecution(new ParameterKey(paramName), value); 86 | } 87 | 88 | /** 89 | * @param index index 90 | * @param sqlType the SQL type code defined in java.sql.Types 91 | * @return {@code this} object. 92 | */ 93 | public static ExecutionParameter nullParam(int index, int sqlType) { 94 | return new SetNullParamExecution(new ParameterKey(index), sqlType); 95 | } 96 | 97 | // do not care sqlType 98 | public static ExecutionParameter nullParam(int index) { 99 | return new SetNullParamExecution(new ParameterKey(index), null); 100 | } 101 | 102 | public static ExecutionParameter nullParam(String name, int sqlType) { 103 | return new SetNullParamExecution(new ParameterKey(name), sqlType); 104 | } 105 | 106 | public static ExecutionParameter nullParam(String name) { 107 | return new SetNullParamExecution(new ParameterKey(name), null); 108 | } 109 | 110 | public static ExecutionParameter outParam(int paramIndex, int sqlType) { 111 | return new RegisterOutParamExecutionWithIntType(new ParameterKey(paramIndex), sqlType); 112 | } 113 | 114 | public static ExecutionParameter outParam(int paramIndex, SQLType sqlType) { 115 | return new RegisterOutParamExecutionWithSQLType(new ParameterKey(paramIndex), sqlType); 116 | } 117 | 118 | public static ExecutionParameter outParam(String paramName, int sqlType) { 119 | return new RegisterOutParamExecutionWithIntType(new ParameterKey(paramName), sqlType); 120 | } 121 | 122 | public static ExecutionParameter outParam(String paramName, SQLType sqlType) { 123 | return new RegisterOutParamExecutionWithSQLType(new ParameterKey(paramName), sqlType); 124 | } 125 | 126 | protected ParameterKey key; 127 | 128 | public ExecutionParameter(ParameterKey key) { 129 | this.key = key; 130 | } 131 | 132 | public ParameterKey.ParameterKeyType getKeyType() { 133 | return this.key.getType(); 134 | } 135 | 136 | public ParameterKey getKey() { 137 | return this.key; 138 | } 139 | 140 | } 141 | -------------------------------------------------------------------------------- /src/main/java/net/ttddyy/dsproxy/asserts/assertj/data/ExecutionParameters.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts.assertj.data; 2 | 3 | import net.ttddyy.dsproxy.proxy.ParameterKey; 4 | 5 | import java.util.ArrayList; 6 | import java.util.Arrays; 7 | import java.util.List; 8 | 9 | /** 10 | * @author Tadaya Tsuyukubo 11 | * @since 1.0 12 | */ 13 | public class ExecutionParameters { 14 | 15 | public enum ExecutionParametersType { 16 | CONTAINS, CONTAINS_EXACTLY, CONTAINS_KEYS_ONLY 17 | } 18 | 19 | public static ExecutionParameters containsParams(ExecutionParameter... params) { 20 | ExecutionParameters executionParameters = new ExecutionParameters(); 21 | executionParameters.type = ExecutionParametersType.CONTAINS; 22 | executionParameters.parameters.addAll(Arrays.asList(params)); 23 | return executionParameters; 24 | } 25 | 26 | public static ExecutionParameters containsParamsExactly(ExecutionParameter... params) { 27 | ExecutionParameters executionParameters = new ExecutionParameters(); 28 | executionParameters.type = ExecutionParametersType.CONTAINS_EXACTLY; 29 | executionParameters.parameters.addAll(Arrays.asList(params)); 30 | return executionParameters; 31 | 32 | } 33 | 34 | public static ExecutionParameters containsParamKeys(Object... paramKeys) { 35 | 36 | List params = new ArrayList<>(); 37 | 38 | for (Object rawParamKey : paramKeys) { 39 | ExecutionParameter param; 40 | if (rawParamKey instanceof Integer) { 41 | param = new ExecutionParameter.ParamKeyOnlyExecution(new ParameterKey((Integer) rawParamKey)); 42 | } else if (rawParamKey instanceof String) { 43 | param = new ExecutionParameter.ParamKeyOnlyExecution(new ParameterKey((String) rawParamKey)); 44 | } else { 45 | throw new IllegalArgumentException("param key should be int or String"); 46 | } 47 | params.add(param); 48 | } 49 | 50 | 51 | ExecutionParameters executionParameters = new ExecutionParameters(); 52 | executionParameters.type = ExecutionParametersType.CONTAINS_KEYS_ONLY; 53 | executionParameters.parameters.addAll(params); 54 | return executionParameters; 55 | } 56 | 57 | public static ExecutionParameters containsParamIndexes(int... paramIndexes) { 58 | 59 | List params = new ArrayList<>(); 60 | for (int paramIndex : paramIndexes) { 61 | ExecutionParameter param = new ExecutionParameter.ParamKeyOnlyExecution(new ParameterKey(paramIndex)); 62 | params.add(param); 63 | } 64 | 65 | ExecutionParameters executionParameters = new ExecutionParameters(); 66 | executionParameters.type = ExecutionParametersType.CONTAINS_KEYS_ONLY; 67 | executionParameters.parameters.addAll(params); 68 | return executionParameters; 69 | } 70 | 71 | public static ExecutionParameters containsParamNames(String... paramNames) { 72 | 73 | List params = new ArrayList<>(); 74 | for (String paramName : paramNames) { 75 | ExecutionParameter param = new ExecutionParameter.ParamKeyOnlyExecution(new ParameterKey(paramName)); 76 | params.add(param); 77 | } 78 | 79 | ExecutionParameters executionParameters = new ExecutionParameters(); 80 | executionParameters.type = ExecutionParametersType.CONTAINS_KEYS_ONLY; 81 | executionParameters.parameters.addAll(params); 82 | return executionParameters; 83 | 84 | } 85 | 86 | private List parameters = new ArrayList<>(); 87 | private ExecutionParametersType type; 88 | 89 | 90 | public List getParameters() { 91 | return parameters; 92 | } 93 | 94 | public ExecutionParametersType getType() { 95 | return type; 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /src/main/java/net/ttddyy/dsproxy/asserts/assertj/helper/AbstractHelperAsserts.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts.assertj.helper; 2 | 3 | import org.assertj.core.api.WritableAssertionInfo; 4 | import org.assertj.core.error.MessageFormatter; 5 | import org.assertj.core.internal.Failures; 6 | 7 | /** 8 | * @author Tadaya Tsuyukubo 9 | * @since 1.0 10 | */ 11 | // TODO: better name 12 | public abstract class AbstractHelperAsserts { 13 | protected WritableAssertionInfo info; 14 | 15 | public AbstractHelperAsserts(WritableAssertionInfo info) { 16 | this.info = info; 17 | } 18 | 19 | // TODO: it's copy from assertj, should find better way. 20 | protected void failWithMessage(String errorMessage, Object... arguments) { 21 | AssertionError failureWithOverriddenErrorMessage = Failures.instance().failureIfErrorMessageIsOverridden(info); 22 | if (failureWithOverriddenErrorMessage != null) throw failureWithOverriddenErrorMessage; 23 | String description = MessageFormatter.instance().format(info.description(), info.representation(), ""); 24 | throw new AssertionError(description + String.format(errorMessage, arguments)); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/net/ttddyy/dsproxy/asserts/assertj/helper/BatchExecutionEntryAsserts.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts.assertj.helper; 2 | 3 | import net.ttddyy.dsproxy.asserts.BatchExecutionEntry; 4 | import net.ttddyy.dsproxy.asserts.BatchParameterHolder; 5 | import net.ttddyy.dsproxy.asserts.ParameterHolder; 6 | import org.assertj.core.api.WritableAssertionInfo; 7 | 8 | import java.util.List; 9 | 10 | /** 11 | * @author Tadaya Tsuyukubo 12 | * @since 1.0 13 | */ 14 | // TODO: better name 15 | public class BatchExecutionEntryAsserts extends AbstractHelperAsserts { 16 | 17 | public BatchExecutionEntryAsserts(WritableAssertionInfo info) { 18 | super(info); 19 | } 20 | 21 | public void assertBatchSize(BatchParameterHolder batchParameterHolder, int batchSize, String batchType) { 22 | int actualSize = batchParameterHolder.getBatchExecutionEntries().size(); 23 | if (actualSize != batchSize) { 24 | failWithMessage("%nExpected batch size:<%s> but was:<%s> in batch %s executions%n", batchSize, actualSize, batchType); 25 | } 26 | } 27 | 28 | public void assertBatchExecutionEntry(BatchParameterHolder batchParameterHolder, int batchIndex, Class batchExecutionEntryClass) { 29 | // validate batch index size 30 | List batchEntries = batchParameterHolder.getBatchExecutionEntries(); 31 | int batchSize = batchEntries.size(); 32 | 33 | if (batchIndex < 0) { 34 | String message = String.format("\nExpecting: batch index <%d> should be greater than equal to <0>", batchIndex); 35 | failWithMessage(message); 36 | } else if (batchSize <= batchIndex) { 37 | String message = String.format("\nExpecting: batch index <%d> is too big for the batch size <%d>", batchIndex, batchSize); 38 | failWithMessage(message); 39 | } 40 | 41 | // validate batch execution entry type 42 | BatchExecutionEntry batchEntry = batchParameterHolder.getBatchExecutionEntries().get(batchIndex); 43 | if (!(batchEntry.getClass().isAssignableFrom(batchExecutionEntryClass))) { 44 | failWithMessage("\nExpecting: batch entry\n<%s>\nbut was\n<%s>", 45 | batchExecutionEntryClass.getSimpleName(), 46 | batchEntry.getClass().getSimpleName()); 47 | } 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/net/ttddyy/dsproxy/asserts/hamcrest/BatchParameterHolderAssertions.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts.hamcrest; 2 | 3 | import net.ttddyy.dsproxy.asserts.BatchExecutionEntry; 4 | import net.ttddyy.dsproxy.asserts.BatchParameterHolder; 5 | import net.ttddyy.dsproxy.asserts.ParameterHolder; 6 | import org.hamcrest.Description; 7 | import org.hamcrest.FeatureMatcher; 8 | import org.hamcrest.Matcher; 9 | 10 | import java.util.List; 11 | 12 | import static org.hamcrest.Matchers.equalTo; 13 | 14 | 15 | /** 16 | * Hamcrest matchers for {@link BatchParameterHolder}. 17 | * 18 | * @author Tadaya Tsuyukubo 19 | * @since 1.0 20 | */ 21 | class BatchParameterHolderAssertions { 22 | 23 | /** 24 | * Matcher to check the batch size. 25 | * 26 | * Example: 27 | *
 assertThat(ds.getBatchStatements(), batchSize(3)); 
28 | */ 29 | public static Matcher batchSize(final int batchSize) { 30 | return new FeatureMatcher(equalTo(batchSize), "batchSize", "batchSize") { 31 | @Override 32 | protected Integer featureValueOf(BatchParameterHolder actual) { 33 | return actual.getBatchExecutionEntries().size(); 34 | } 35 | }; 36 | } 37 | 38 | /** 39 | * Matcher to check the given index in batch matches with given parameter matcher. 40 | * 41 | * Example: 42 | *
 assertThat(ds.getBatchStatements(), batch(0, param(1, String.class, is("FOO")))); 
43 | */ 44 | public static Matcher batch(final int index, final Matcher parameterHolderMatcher) { 45 | return new CompositeMatcher(parameterHolderMatcher) { 46 | @Override 47 | protected boolean validateByThisMatcher(BatchParameterHolder item, Description expected, Description actual) { 48 | List entries = item.getBatchExecutionEntries(); 49 | int size = entries.size(); 50 | if (size - 1 < index) { 51 | expected.appendText("batch[" + index + "] exists"); 52 | actual.appendText("batch[] size was " + size); 53 | return false; 54 | } 55 | 56 | BatchExecutionEntry entry = entries.get(index); 57 | if (!(entry instanceof ParameterHolder)) { // TODO: unit asserts 58 | expected.appendText("batch[" + index + "] an instance of " + ParameterHolder.class.getSimpleName()); 59 | actual.appendText("batch[" + index + "] is a " + item.getClass().getName()); 60 | return false; 61 | } 62 | 63 | return true; 64 | } 65 | 66 | @Override 67 | public ParameterHolder getValue(BatchParameterHolder actual) { 68 | BatchExecutionEntry entry = actual.getBatchExecutionEntries().get(index); 69 | return (ParameterHolder) entry; 70 | } 71 | 72 | @Override 73 | public String getSubMatcherFailureDescriptionPrefix() { 74 | return "batch[" + index + "] "; 75 | } 76 | }; 77 | 78 | } 79 | 80 | } 81 | -------------------------------------------------------------------------------- /src/main/java/net/ttddyy/dsproxy/asserts/hamcrest/CompositeMatcher.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts.hamcrest; 2 | 3 | import org.hamcrest.BaseMatcher; 4 | import org.hamcrest.Description; 5 | import org.hamcrest.Matcher; 6 | import org.hamcrest.StringDescription; 7 | import org.hamcrest.internal.ReflectiveTypeFinder; 8 | 9 | /** 10 | * Since {@link org.hamcrest.FeatureMatcher} doesn't support flexible error messaging, this class provides callbacks 11 | * for error message. 12 | * 13 | * @param type for this matcher 14 | * @param type for sub-matcher 15 | * @author Tadaya Tsuyukubo 16 | * @since 1.0 17 | */ 18 | public abstract class CompositeMatcher extends BaseMatcher { 19 | private static final ReflectiveTypeFinder TYPE_FINDER = new ReflectiveTypeFinder("getValue", 1, 0); 20 | 21 | protected Matcher subMatcher; 22 | private Class expectedType; 23 | protected Description expected = new StringDescription(); 24 | protected Description actual = new StringDescription(); 25 | 26 | protected CompositeMatcher(Matcher subMatcher) { 27 | this.subMatcher = subMatcher; 28 | this.expectedType = TYPE_FINDER.findExpectedType(getClass()); 29 | } 30 | 31 | 32 | @Override 33 | @SuppressWarnings({"unchecked"}) 34 | public boolean matches(Object item) { 35 | 36 | if (!expectedType.isInstance(item)) { 37 | this.expected.appendText(this.expectedType.getName()); 38 | this.actual.appendText("was a ") 39 | .appendText(item.getClass().getName()) 40 | .appendText(" (") 41 | .appendValue(item) 42 | .appendText(")"); 43 | return false; 44 | } 45 | 46 | T safelyConverted = (T) item; 47 | if (!validateByThisMatcher(safelyConverted, this.expected, this.actual)) { 48 | return false; 49 | } 50 | 51 | S targetValue = getValue(safelyConverted); 52 | if (!this.subMatcher.matches(targetValue)) { 53 | this.describeExpectedBySubMatcher(this.subMatcher, targetValue, this.expected, this.actual); 54 | return false; 55 | } 56 | return true; 57 | } 58 | 59 | public abstract S getValue(T actual); 60 | 61 | protected boolean validateByThisMatcher(T item, Description expected, Description actual) { 62 | return true; 63 | } 64 | 65 | protected void describeExpectedBySubMatcher(Matcher subMatcher, S targetValue, Description expected, Description actual) { 66 | String prefix = getSubMatcherFailureDescriptionPrefix(); 67 | if (prefix != null) { 68 | expected.appendText(prefix); 69 | actual.appendText(prefix); 70 | } 71 | 72 | subMatcher.describeTo(expected); 73 | subMatcher.describeMismatch(targetValue, actual); 74 | } 75 | 76 | public abstract String getSubMatcherFailureDescriptionPrefix(); 77 | 78 | 79 | @Override 80 | public void describeTo(Description description) { 81 | // for expected message 82 | description.appendText(this.expected.toString()); 83 | } 84 | 85 | @Override 86 | public void describeMismatch(Object item, Description description) { 87 | // for actual(but was) message 88 | description.appendText(this.actual.toString()); 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /src/main/java/net/ttddyy/dsproxy/asserts/hamcrest/ExecutionType.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts.hamcrest; 2 | 3 | import net.ttddyy.dsproxy.asserts.CallableBatchExecution; 4 | import net.ttddyy.dsproxy.asserts.CallableExecution; 5 | import net.ttddyy.dsproxy.asserts.PreparedBatchExecution; 6 | import net.ttddyy.dsproxy.asserts.PreparedExecution; 7 | import net.ttddyy.dsproxy.asserts.QueryExecution; 8 | import net.ttddyy.dsproxy.asserts.StatementBatchExecution; 9 | import net.ttddyy.dsproxy.asserts.StatementExecution; 10 | 11 | /** 12 | * @author Tadaya Tsuyukubo 13 | * @since 1.0 14 | */ 15 | public enum ExecutionType { 16 | 17 | IS_BATCH("batch", StatementBatchExecution.class, PreparedBatchExecution.class, CallableBatchExecution.class), 18 | IS_STATEMENT("statement", StatementExecution.class), 19 | IS_BATCH_STATEMENT("batch statement", StatementBatchExecution.class), 20 | IS_STATEMENT_OR_BATCH_STATEMENT("statement or batch statement", StatementExecution.class, StatementBatchExecution.class), 21 | IS_PREPARED("prepared", PreparedExecution.class), 22 | IS_BATCH_PREPARED("batch prepared", PreparedBatchExecution.class), 23 | IS_PREPARED_OR_BATCH_PREPARED("prepared or batch prepared", PreparedExecution.class, PreparedBatchExecution.class), 24 | IS_CALLABLE("callable", CallableExecution.class), 25 | IS_BATCH_CALLABLE("batch callable", CallableBatchExecution.class), 26 | IS_CALLABLE_OR_BATCH_CALLABLE("callable or batch callable", CallableExecution.class, CallableBatchExecution.class); 27 | 28 | 29 | private String description; 30 | private Class[] executionTypes; 31 | 32 | @SafeVarargs 33 | ExecutionType(String description, Class... executionTypes) { 34 | this.description = description; 35 | this.executionTypes = executionTypes; 36 | } 37 | 38 | public static ExecutionType valueOf(QueryExecution queryExecution) { 39 | if (queryExecution instanceof StatementExecution) { 40 | return IS_STATEMENT; 41 | } else if (queryExecution instanceof StatementBatchExecution) { 42 | return IS_BATCH_STATEMENT; 43 | } else if (queryExecution instanceof PreparedExecution) { 44 | return IS_PREPARED; 45 | } else if (queryExecution instanceof PreparedBatchExecution) { 46 | return IS_BATCH_PREPARED; 47 | } else if (queryExecution instanceof CallableExecution) { 48 | return IS_CALLABLE; 49 | } else if (queryExecution instanceof CallableBatchExecution) { 50 | return IS_BATCH_CALLABLE; 51 | } 52 | return null; 53 | } 54 | 55 | public String getDescription() { 56 | return this.description; 57 | } 58 | 59 | public Class[] getExecutionTypes() { 60 | return this.executionTypes; 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/net/ttddyy/dsproxy/asserts/hamcrest/ExecutionTypeMatcher.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts.hamcrest; 2 | 3 | import net.ttddyy.dsproxy.asserts.QueryExecution; 4 | import org.hamcrest.Description; 5 | import org.hamcrest.TypeSafeMatcher; 6 | 7 | /** 8 | * @author Tadaya Tsuyukubo 9 | * @since 1.0 10 | */ 11 | public class ExecutionTypeMatcher extends TypeSafeMatcher { 12 | 13 | private ExecutionType expectedType; 14 | 15 | public ExecutionTypeMatcher(ExecutionType expected) { 16 | this.expectedType = expected; 17 | } 18 | 19 | @Override 20 | protected boolean matchesSafely(QueryExecution item) { 21 | for (Class executionTypeClass : expectedType.getExecutionTypes()) { 22 | if (item.getClass().isAssignableFrom(executionTypeClass)) { 23 | return true; 24 | } 25 | } 26 | return false; 27 | } 28 | 29 | @Override 30 | public void describeTo(Description description) { 31 | description.appendText(this.expectedType.getDescription()); 32 | } 33 | 34 | @Override 35 | protected void describeMismatchSafely(QueryExecution item, Description mismatchDescription) { 36 | mismatchDescription.appendText("was "); 37 | 38 | ExecutionType executionType = ExecutionType.valueOf(item); 39 | if (executionType == null) { 40 | mismatchDescription.appendText(null); 41 | } else { 42 | mismatchDescription.appendText(executionType.getDescription()); 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/net/ttddyy/dsproxy/asserts/hamcrest/ParameterHolderMatcher.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts.hamcrest; 2 | 3 | import net.ttddyy.dsproxy.asserts.OutParameterHolder; 4 | import net.ttddyy.dsproxy.asserts.ParameterByIndexHolder; 5 | import net.ttddyy.dsproxy.asserts.ParameterByNameHolder; 6 | import net.ttddyy.dsproxy.asserts.ParameterHolder; 7 | import org.hamcrest.BaseMatcher; 8 | import org.hamcrest.Description; 9 | import org.hamcrest.Matcher; 10 | import org.hamcrest.StringDescription; 11 | 12 | /** 13 | * @author Tadaya Tsuyukubo 14 | * @since 1.0 15 | */ 16 | public abstract class ParameterHolderMatcher extends BaseMatcher { 17 | 18 | protected enum MatchBy { 19 | INDEX, NAME, OUTPARAM 20 | } 21 | 22 | private final Matcher subMatcher; 23 | private MatchBy matchBy; 24 | 25 | protected Description descForExpected = new StringDescription(); 26 | protected Description descForFailure = new StringDescription(); 27 | 28 | protected ParameterHolderMatcher(Matcher subMatcher, MatchBy matchBy) { 29 | this.subMatcher = subMatcher; 30 | this.matchBy = matchBy; 31 | } 32 | 33 | 34 | @Override 35 | public boolean matches(Object item) { 36 | 37 | if (!(item instanceof ParameterHolder)) { 38 | populateCompatibilityFailureMessage(ParameterHolder.class, item); 39 | return false; 40 | } 41 | ParameterHolder holder = (ParameterHolder) item; 42 | 43 | S featureValue; 44 | if (MatchBy.INDEX.equals(this.matchBy)) { 45 | if (!(holder instanceof ParameterByIndexHolder)) { 46 | populateCompatibilityFailureMessage(ParameterByIndexHolder.class, holder); 47 | return false; 48 | } 49 | ParameterByIndexHolder byIndexHolder = (ParameterByIndexHolder) holder; 50 | if (!validateParameterByIndex(byIndexHolder, this.descForExpected, this.descForFailure)) { 51 | return false; // validation failure 52 | } 53 | featureValue = getFeatureValue(byIndexHolder); 54 | } else if (MatchBy.NAME.equals(this.matchBy)) { 55 | if (!(holder instanceof ParameterByNameHolder)) { 56 | populateCompatibilityFailureMessage(ParameterByNameHolder.class, holder); 57 | return false; 58 | } 59 | ParameterByNameHolder byNameHolder = (ParameterByNameHolder) holder; 60 | if (!validateParameterByName(byNameHolder, this.descForExpected, this.descForFailure)) { 61 | return false; // validation failure 62 | } 63 | featureValue = getFeatureValue(byNameHolder); 64 | } else { 65 | if (!(holder instanceof OutParameterHolder)) { 66 | populateCompatibilityFailureMessage(OutParameterHolder.class, holder); 67 | return false; 68 | } 69 | OutParameterHolder byOutParamHolder = (OutParameterHolder) holder; 70 | if (!validateParameterByOutParam(byOutParamHolder, this.descForExpected, this.descForFailure)) { 71 | return false; // validation failure 72 | } 73 | featureValue = getFeatureValue(byOutParamHolder); 74 | } 75 | 76 | if (!this.subMatcher.matches(featureValue)) { 77 | Description description = new StringDescription(); 78 | this.subMatcher.describeMismatch(featureValue, description); // get mismatch desc 79 | this.descForExpected.appendDescriptionOf(subMatcher); // populate from SelfDescribing 80 | this.descForFailure.appendText(description.toString()); 81 | return false; 82 | } 83 | 84 | return true; 85 | } 86 | 87 | private void populateCompatibilityFailureMessage(Class expectedInterface, Object actual) { 88 | String interfaceName = expectedInterface.getSimpleName(); 89 | this.descForExpected.appendText("implementation of ").appendText(interfaceName); 90 | this.descForFailure.appendText(actual.getClass().getSimpleName()).appendText(" didn't implement ").appendText(interfaceName); 91 | } 92 | 93 | public S getFeatureValue(ParameterByIndexHolder actual) { 94 | throw new UnsupportedOperationException("Subclass that uses byIndex should implement this method."); 95 | } 96 | 97 | public S getFeatureValue(ParameterByNameHolder actual) { 98 | throw new UnsupportedOperationException("Subclass that uses byName should implement this method."); 99 | } 100 | 101 | public S getFeatureValue(OutParameterHolder actual) { 102 | throw new UnsupportedOperationException("Subclass that uses byName should implement this method."); 103 | } 104 | 105 | public boolean validateParameterByIndex(ParameterByIndexHolder actual, Description descForExpected, Description descForFailure) { 106 | return true; 107 | } 108 | 109 | public boolean validateParameterByName(ParameterByNameHolder actual, Description descForExpected, Description descForFailure) { 110 | return true; 111 | } 112 | 113 | public boolean validateParameterByOutParam(OutParameterHolder actual, Description descForExpected, Description descForFailure) { 114 | return true; 115 | } 116 | 117 | @Override 118 | public void describeTo(Description description) { 119 | description.appendText(this.descForExpected.toString()); 120 | } 121 | 122 | @Override 123 | public void describeMismatch(Object item, Description description) { 124 | description.appendText(this.descForFailure.toString()); 125 | } 126 | 127 | public static abstract class ParameterByIndexMatcher extends ParameterHolderMatcher { 128 | 129 | public ParameterByIndexMatcher(Matcher subMatcher) { 130 | super(subMatcher, MatchBy.INDEX); 131 | } 132 | 133 | @Override 134 | public T getFeatureValue(ParameterByIndexHolder actual) { 135 | return featureValueOf(actual); 136 | } 137 | 138 | public abstract T featureValueOf(ParameterByIndexHolder actual); 139 | } 140 | 141 | public static abstract class ParameterByNameMatcher extends ParameterHolderMatcher { 142 | 143 | public ParameterByNameMatcher(Matcher subMatcher) { 144 | super(subMatcher, MatchBy.NAME); 145 | } 146 | 147 | @Override 148 | public T getFeatureValue(ParameterByNameHolder actual) { 149 | return featureValueOf(actual); 150 | } 151 | 152 | public abstract T featureValueOf(ParameterByNameHolder actual); 153 | } 154 | 155 | public static abstract class OutParamMatcher extends ParameterHolderMatcher { 156 | 157 | public OutParamMatcher(Matcher subMatcher) { 158 | super(subMatcher, MatchBy.OUTPARAM); 159 | } 160 | 161 | @Override 162 | public T getFeatureValue(OutParameterHolder actual) { 163 | return featureValueOf(actual); 164 | } 165 | 166 | public abstract T featureValueOf(OutParameterHolder actual); 167 | } 168 | } 169 | -------------------------------------------------------------------------------- /src/main/java/net/ttddyy/dsproxy/asserts/hamcrest/QueriesHolderAssertions.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts.hamcrest; 2 | 3 | import net.ttddyy.dsproxy.asserts.QueriesHolder; 4 | import net.ttddyy.dsproxy.asserts.QueryHolder; 5 | import org.hamcrest.Description; 6 | import org.hamcrest.FeatureMatcher; 7 | import org.hamcrest.Matcher; 8 | 9 | import java.util.Collection; 10 | 11 | /** 12 | * Hamcrest matchers for {@link QueriesHolder}. 13 | * 14 | * @author Tadaya Tsuyukubo 15 | * @since 1.0 16 | */ 17 | class QueriesHolderAssertions { 18 | 19 | /** 20 | * Matcher to check the specified index query as {@link String}. 21 | * 22 | * Example: 23 | *
 assertThat(ds.getFirstBatchStatement(), queries(0, startsWith("INSERT"))); 
24 | */ 25 | public static Matcher queries(final int index, Matcher stringMatcher) { 26 | return new CompositeMatcher(stringMatcher) { 27 | @Override 28 | protected boolean validateByThisMatcher(QueriesHolder item, Description expected, Description actual) { 29 | int size = item.getQueries().size(); 30 | if (size - 1 < index) { 31 | expected.appendText("queries[" + index + "] exists"); 32 | actual.appendText("queries[] size was " + size); 33 | return false; 34 | } 35 | return true; 36 | } 37 | 38 | @Override 39 | public String getValue(QueriesHolder actual) { 40 | return actual.getQueries().get(index); 41 | } 42 | 43 | @Override 44 | public String getSubMatcherFailureDescriptionPrefix() { 45 | return "queries[" + index + "] "; 46 | } 47 | 48 | }; 49 | } 50 | 51 | /** 52 | * Matcher to check the given queries with string collection matcher. 53 | * 54 | * Example: 55 | *
 assertThat(ds.getFirstBatchStatement(), queries(hasItems("foo", "bar"))); 
56 | */ 57 | public static Matcher queries(Matcher> collectionMatcher) { 58 | return new FeatureMatcher>(collectionMatcher, "queries[]", "queries[]") { 59 | @Override 60 | protected Collection featureValueOf(QueriesHolder actual) { 61 | return actual.getQueries(); 62 | } 63 | }; 64 | } 65 | 66 | /** 67 | * Matcher to check the specified index query as {@link String}. 68 | * 69 | * Example: 70 | *
 assertThat(ds.getFirstBatchStatement(), queryTypes(0, select())); 
71 | */ 72 | public static Matcher queryTypes(final int index, Matcher queryHolderMatcher) { 73 | return new CompositeMatcher(queryHolderMatcher) { 74 | @Override 75 | protected boolean validateByThisMatcher(QueriesHolder item, Description expected, Description actual) { 76 | int size = item.getQueries().size(); 77 | if (size - 1 < index) { 78 | expected.appendText("queries[" + index + "] exists"); 79 | actual.appendText("queries[] size was " + size); 80 | return false; 81 | } 82 | return true; 83 | } 84 | 85 | @Override 86 | public QueryHolder getValue(QueriesHolder actual) { 87 | // convert query to a placeholder QueryHolder instance 88 | final String query = actual.getQueries().get(index); 89 | QueryHolder queryHolder = new QueryHolder() { 90 | @Override 91 | public String getQuery() { 92 | return query; 93 | } 94 | }; 95 | return queryHolder; 96 | } 97 | 98 | @Override 99 | public String getSubMatcherFailureDescriptionPrefix() { 100 | return "queries[" + index + "] "; 101 | } 102 | 103 | }; 104 | } 105 | 106 | 107 | } 108 | -------------------------------------------------------------------------------- /src/main/java/net/ttddyy/dsproxy/asserts/hamcrest/QueryExecutionAssertions.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts.hamcrest; 2 | 3 | import net.ttddyy.dsproxy.asserts.QueryExecution; 4 | import org.hamcrest.Description; 5 | import org.hamcrest.Matcher; 6 | import org.hamcrest.TypeSafeMatcher; 7 | 8 | /** 9 | * Hamcrest matchers for {@link QueryExecution}. 10 | * 11 | * @author Tadaya Tsuyukubo 12 | * @since 1.0 13 | */ 14 | class QueryExecutionAssertions { 15 | 16 | /** 17 | * Matcher to check {@link QueryExecution} was successful. 18 | * 19 | * Example: 20 | *
 assertThat(qe, success()); 
21 | */ 22 | public static Matcher success() { 23 | return new TypeSafeMatcher() { 24 | @Override 25 | protected boolean matchesSafely(QueryExecution item) { 26 | return item.isSuccess(); 27 | } 28 | 29 | @Override 30 | public void describeTo(Description description) { 31 | description.appendText("success"); 32 | } 33 | 34 | @Override 35 | protected void describeMismatchSafely(QueryExecution item, Description mismatchDescription) { 36 | mismatchDescription.appendText("was failure"); 37 | } 38 | }; 39 | } 40 | 41 | /** 42 | * Matcher to check {@link QueryExecution} was failure. 43 | * 44 | * Example: 45 | *
 assertThat(qe, failure()); 
46 | */ 47 | public static Matcher failure() { 48 | return new TypeSafeMatcher() { 49 | @Override 50 | protected boolean matchesSafely(QueryExecution item) { 51 | return !item.isSuccess(); 52 | } 53 | 54 | @Override 55 | public void describeTo(Description description) { 56 | description.appendText("failure"); 57 | } 58 | 59 | @Override 60 | protected void describeMismatchSafely(QueryExecution item, Description mismatchDescription) { 61 | mismatchDescription.appendText("was success"); 62 | } 63 | }; 64 | } 65 | 66 | /** 67 | * Matcher to check {@link QueryExecution} was a batch execution. 68 | * 69 | * Example: 70 | *
 assertThat(qe, batch()); 
71 | */ 72 | public static Matcher batch() { 73 | return new ExecutionTypeMatcher(ExecutionType.IS_BATCH); 74 | } 75 | 76 | 77 | /** 78 | * Matcher to check {@link QueryExecution} was an execution of {@link java.sql.Statement}. 79 | * 80 | * Example: 81 | *
 assertThat(qe, statement()); 
82 | */ 83 | public static Matcher statement() { 84 | return new ExecutionTypeMatcher(ExecutionType.IS_STATEMENT); 85 | } 86 | 87 | /** 88 | * Matcher to check {@link QueryExecution} was a batch execution of {@link java.sql.Statement}. 89 | * 90 | * Example: 91 | *
 assertThat(qe, batchStatement()); 
92 | */ 93 | public static Matcher batchStatement() { 94 | return new ExecutionTypeMatcher(ExecutionType.IS_BATCH_STATEMENT); 95 | } 96 | 97 | /** 98 | * Matcher to check {@link QueryExecution} was a normal or batch execution of {@link java.sql.Statement}. 99 | * 100 | * Example: 101 | *
 assertThat(qe, statementOrBatchStatement()); 
102 | */ 103 | public static Matcher statementOrBatchStatement() { 104 | return new ExecutionTypeMatcher(ExecutionType.IS_STATEMENT_OR_BATCH_STATEMENT); 105 | } 106 | 107 | /** 108 | * Matcher to check {@link QueryExecution} was an execution of {@link java.sql.PreparedStatement}. 109 | * 110 | * Example: 111 | *
 assertThat(qe, prepared()); 
112 | */ 113 | public static Matcher prepared() { 114 | return new ExecutionTypeMatcher(ExecutionType.IS_PREPARED); 115 | } 116 | 117 | /** 118 | * Matcher to check {@link QueryExecution} was a batch execution of {@link java.sql.PreparedStatement}. 119 | * 120 | * Example: 121 | *
 assertThat(qe, batchPrepared()); 
122 | */ 123 | public static Matcher batchPrepared() { 124 | return new ExecutionTypeMatcher(ExecutionType.IS_BATCH_PREPARED); 125 | } 126 | 127 | /** 128 | * Matcher to check {@link QueryExecution} was a normal or batch execution of {@link java.sql.PreparedStatement}. 129 | * 130 | * Example: 131 | *
 assertThat(qe, preparedOrBatchPrepared()); 
132 | */ 133 | public static Matcher preparedOrBatchPrepared() { 134 | return new ExecutionTypeMatcher(ExecutionType.IS_PREPARED_OR_BATCH_PREPARED); 135 | } 136 | 137 | /** 138 | * Matcher to check {@link QueryExecution} was an execution of {@link java.sql.CallableStatement}. 139 | * 140 | * Example: 141 | *
 assertThat(qe, callable()); 
142 | */ 143 | public static Matcher callable() { 144 | return new ExecutionTypeMatcher(ExecutionType.IS_CALLABLE); 145 | } 146 | 147 | /** 148 | * Matcher to check {@link QueryExecution} was a batch execution of {@link java.sql.CallableStatement}. 149 | * 150 | * Example: 151 | *
 assertThat(qe, batchCallable()); 
152 | */ 153 | public static Matcher batchCallable() { 154 | return new ExecutionTypeMatcher(ExecutionType.IS_BATCH_CALLABLE); 155 | } 156 | 157 | /** 158 | * Matcher to check {@link QueryExecution} was a normal or batch execution of {@link java.sql.CallableStatement}. 159 | * 160 | * Example: 161 | *
 assertThat(qe, callableOrBatchCallable()); 
162 | */ 163 | public static Matcher callableOrBatchCallable() { 164 | return new ExecutionTypeMatcher(ExecutionType.IS_CALLABLE_OR_BATCH_CALLABLE); 165 | } 166 | 167 | } 168 | -------------------------------------------------------------------------------- /src/main/java/net/ttddyy/dsproxy/asserts/hamcrest/QueryHolderAssertions.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts.hamcrest; 2 | 3 | import net.ttddyy.dsproxy.QueryType; 4 | import net.ttddyy.dsproxy.asserts.QueryHolder; 5 | import net.ttddyy.dsproxy.listener.QueryUtils; 6 | import org.hamcrest.Description; 7 | import org.hamcrest.FeatureMatcher; 8 | import org.hamcrest.Matcher; 9 | import org.hamcrest.TypeSafeMatcher; 10 | 11 | /** 12 | * Hamcrest matchers for {@link QueryHolder}. 13 | * 14 | * @author Tadaya Tsuyukubo 15 | * @since 1.0 16 | */ 17 | class QueryHolderAssertions { 18 | 19 | /** 20 | * Matcher to examine the query with given {@link String} matcher. 21 | * 22 | * Example: 23 | *
 assertThat(qe, query(startsWith("select"))); 
24 | */ 25 | public static Matcher query(final Matcher stringMatcher) { 26 | return new FeatureMatcher(stringMatcher, "query", "query") { 27 | @Override 28 | protected String featureValueOf(QueryHolder actual) { 29 | return actual.getQuery(); 30 | } 31 | }; 32 | } 33 | 34 | /** 35 | * Matcher to examine the query type. 36 | * 37 | * Example: 38 | *
 assertThat(qe, queryType(SELECT)); 
39 | */ 40 | public static Matcher queryType(final QueryType expectedType) { 41 | 42 | return new TypeSafeMatcher() { 43 | @Override 44 | protected boolean matchesSafely(QueryHolder item) { 45 | String query = item.getQuery(); 46 | QueryType actualType = QueryUtils.getQueryType(query); 47 | if (expectedType != actualType) { 48 | return false; 49 | } 50 | return true; 51 | } 52 | 53 | @Override 54 | public void describeTo(Description description) { 55 | // expected clause 56 | description.appendText("query type \"" + expectedType + "\""); 57 | } 58 | 59 | @Override 60 | protected void describeMismatchSafely(QueryHolder item, Description mismatchDescription) { 61 | // but was clause 62 | String query = item.getQuery(); 63 | QueryType actualType = QueryUtils.getQueryType(query); 64 | 65 | String msg = "query type was \"" + actualType + "\" (" + query + ")"; 66 | mismatchDescription.appendText(msg); 67 | } 68 | }; 69 | } 70 | 71 | /** 72 | * Matcher to examine the query type is SELECT. 73 | * 74 | * Example: 75 | *
 assertThat(qe, select()); 
76 | */ 77 | public static Matcher select() { 78 | return queryType(QueryType.SELECT); 79 | } 80 | 81 | /** 82 | * Matcher to examine the query type is SELECT. 83 | * 84 | * Example: 85 | *
 assertThat(qe, insert()); 
86 | */ 87 | public static Matcher insert() { 88 | return queryType(QueryType.INSERT); 89 | } 90 | 91 | /** 92 | * Matcher to examine the query type is SELECT. 93 | * 94 | * Example: 95 | *
 assertThat(qe, update()); 
96 | */ 97 | public static Matcher update() { 98 | return queryType(QueryType.UPDATE); 99 | } 100 | 101 | /** 102 | * Matcher to examine the query type is SELECT. 103 | * 104 | * Example: 105 | *
 assertThat(qe, delete()); 
106 | */ 107 | public static Matcher delete() { 108 | return queryType(QueryType.DELETE); 109 | } 110 | 111 | /** 112 | * Matcher to examine the query type is SELECT. 113 | * 114 | * Example: 115 | *
 assertThat(qe, other()); 
116 | */ 117 | public static Matcher other() { 118 | return queryType(QueryType.OTHER); 119 | } 120 | 121 | } 122 | -------------------------------------------------------------------------------- /src/main/java/net/ttddyy/dsproxy/asserts/hamcrest/SqlTypeMatcher.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts.hamcrest; 2 | 3 | import org.hamcrest.Description; 4 | import org.hamcrest.TypeSafeMatcher; 5 | 6 | import java.lang.reflect.Field; 7 | import java.sql.Types; 8 | import java.util.HashMap; 9 | import java.util.Map; 10 | 11 | /** 12 | * Hamcrest matcher for {@link java.sql.Types}(int). 13 | * 14 | * @author Tadaya Tsuyukubo 15 | * @see java.sql.Types 16 | * @since 1.0 17 | */ 18 | public class SqlTypeMatcher extends TypeSafeMatcher { 19 | 20 | public static final Map typeNameByValue = new HashMap<>(); 21 | 22 | static { 23 | try { 24 | Field[] fields = Types.class.getDeclaredFields(); 25 | for (Field field : fields) { 26 | typeNameByValue.put(field.getInt(null), field.getName()); 27 | } 28 | } catch (Exception e) { 29 | } 30 | } 31 | 32 | protected int expectedSqlType; 33 | protected String messagePrefix = ""; 34 | protected String messageSuffix = ""; 35 | 36 | public SqlTypeMatcher(int expectedSqlType) { 37 | this.expectedSqlType = expectedSqlType; 38 | } 39 | 40 | public SqlTypeMatcher(int expectedSqlType, String messagePrefix, String messageSuffix) { 41 | this.expectedSqlType = expectedSqlType; 42 | this.messagePrefix = messagePrefix; 43 | this.messageSuffix = messageSuffix; 44 | } 45 | 46 | @Override 47 | protected boolean matchesSafely(Integer item) { 48 | if (item == null) { 49 | return false; 50 | } 51 | return this.expectedSqlType == item; 52 | } 53 | 54 | 55 | @Override 56 | public void describeTo(Description description) { 57 | // expected message 58 | description.appendText(getMessage(this.expectedSqlType)); 59 | } 60 | 61 | @Override 62 | protected void describeMismatchSafely(Integer item, Description mismatchDescription) { 63 | // for actual(but was) message 64 | mismatchDescription.appendText(getMessage(item)); 65 | } 66 | 67 | protected String getMessage(Integer sqlType) { 68 | String typeName = typeNameByValue.get(sqlType); 69 | if (typeName == null) { 70 | typeName = "UNKNOWN"; 71 | } 72 | return this.messagePrefix + typeName + ":" + sqlType + this.messageSuffix; 73 | } 74 | 75 | public void setMessagePrefix(String messagePrefix) { 76 | this.messagePrefix = messagePrefix; 77 | } 78 | 79 | public void setMessageSuffix(String messageSuffix) { 80 | this.messageSuffix = messageSuffix; 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/test/java/net/ttddyy/dsproxy/asserts/DatabaseTestRule.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts; 2 | 3 | import org.flywaydb.core.Flyway; 4 | import org.hsqldb.jdbc.JDBCDataSource; 5 | import org.junit.rules.ExternalResource; 6 | 7 | import javax.sql.DataSource; 8 | 9 | /** 10 | * @author Tadaya Tsuyukubo 11 | * @since 1.0 12 | */ 13 | public class DatabaseTestRule extends ExternalResource { 14 | 15 | public DataSource dataSource; 16 | 17 | private Flyway flyway; 18 | 19 | @Override 20 | protected void before() throws Throwable { 21 | 22 | // prepare ds 23 | JDBCDataSource ds = new JDBCDataSource(); 24 | ds.setDatabase("jdbc:hsqldb:mem:aname"); 25 | ds.setUser("sa"); 26 | this.dataSource = ds; 27 | 28 | // populate data 29 | this.flyway = new Flyway(); 30 | this.flyway.setDataSource(ds); 31 | this.flyway.migrate(); 32 | 33 | } 34 | 35 | @Override 36 | protected void after() { 37 | flyway.clean(); 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /src/test/java/net/ttddyy/dsproxy/asserts/ParameterKeyValueTest.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts; 2 | 3 | import org.junit.Test; 4 | 5 | import java.util.SortedSet; 6 | import java.util.TreeSet; 7 | 8 | import static net.ttddyy.dsproxy.asserts.ParameterKeyValueUtils.createRegisterOut; 9 | import static net.ttddyy.dsproxy.asserts.ParameterKeyValueUtils.createSetParam; 10 | import static org.assertj.core.api.Assertions.assertThat; 11 | 12 | /** 13 | * @author Tadaya Tsuyukubo 14 | */ 15 | public class ParameterKeyValueTest { 16 | 17 | @Test 18 | public void compareToIndex() { 19 | SortedSet set = new TreeSet<>(); 20 | set.add(createSetParam(1, 10)); 21 | set.add(createSetParam(3, 10)); 22 | set.add(createSetParam(2, 10)); 23 | 24 | assertThat(set).hasSize(3).extracting("key.index").containsExactly(1, 2, 3); 25 | } 26 | 27 | @Test 28 | public void compareToSameIndex() { 29 | SortedSet set = new TreeSet<>(); 30 | set.add(createSetParam(1, 10)); 31 | set.add(createSetParam(1, 30)); 32 | set.add(createSetParam(1, 20)); 33 | 34 | assertThat(set).hasSize(3).extracting("key.index").containsExactly(1, 1, 1); 35 | 36 | // value will be insertion order 37 | assertThat(set).extracting("value").containsExactly(10, 30, 20); 38 | } 39 | 40 | @Test 41 | public void compareToSameIndexDifferentValueType() { 42 | SortedSet set = new TreeSet<>(); 43 | set.add(createSetParam(1, 10)); 44 | set.add(createSetParam(1, "30")); 45 | set.add(createSetParam(1, 20)); 46 | 47 | assertThat(set).hasSize(3).extracting("key.index").containsExactly(1, 1, 1); 48 | 49 | // value will be insertion order 50 | assertThat(set).extracting("value").containsExactly(10, "30", 20); 51 | } 52 | 53 | @Test 54 | public void compareToDifferentValue() { 55 | SortedSet set = new TreeSet<>(); 56 | set.add(createSetParam(1, null)); 57 | set.add(createRegisterOut(1, null)); 58 | set.add(createSetParam(1, null)); // same key, value again 59 | 60 | // regardless operation type, it only checks key & value 61 | assertThat(set).hasSize(1).extracting("key.index").containsExactly(1); 62 | } 63 | 64 | @Test 65 | public void compareToDifferentKeyTypeWithInt() { 66 | SortedSet set = new TreeSet<>(); 67 | set.add(createSetParam(1, 10)); 68 | set.add(createSetParam("10", 20)); 69 | set.add(createSetParam(1, 20)); 70 | 71 | // regardless operation type, it only checks key & value 72 | assertThat(set).hasSize(3).extracting("key.keyAsString").containsExactly("1", "1", "10"); 73 | } 74 | 75 | @Test 76 | public void compareToNumberKeyInString() { 77 | SortedSet set = new TreeSet<>(); 78 | set.add(createSetParam(1, 10)); 79 | set.add(createSetParam("1", 20)); 80 | 81 | assertThat(set).hasSize(2).extracting("key.keyAsString").containsExactly("1", "1"); 82 | assertThat(set).extracting("value").containsExactly(10, 20); 83 | } 84 | 85 | @Test 86 | public void compareToDifferentKeyType() { 87 | SortedSet set = new TreeSet<>(); 88 | set.add(createSetParam(1, 10)); 89 | set.add(createSetParam("foo", 200)); 90 | set.add(createSetParam(1, 20)); 91 | set.add(createSetParam("bar", 300)); 92 | 93 | // regardless operation type, it only checks key & value 94 | assertThat(set).hasSize(4).extracting("key.keyAsString").containsExactly("1", "1", "bar", "foo"); 95 | assertThat(set).extracting("value").containsExactly(10, 20, 300, 200); 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /src/test/java/net/ttddyy/dsproxy/asserts/assertj/QueryExecutionAssertTest.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts.assertj; 2 | 3 | import net.ttddyy.dsproxy.asserts.CallableBatchExecution; 4 | import net.ttddyy.dsproxy.asserts.CallableExecution; 5 | import net.ttddyy.dsproxy.asserts.PreparedBatchExecution; 6 | import net.ttddyy.dsproxy.asserts.PreparedExecution; 7 | import net.ttddyy.dsproxy.asserts.QueryExecution; 8 | import net.ttddyy.dsproxy.asserts.StatementBatchExecution; 9 | import net.ttddyy.dsproxy.asserts.StatementExecution; 10 | import org.junit.Test; 11 | 12 | import static org.assertj.core.api.Assertions.assertThat; 13 | import static org.junit.Assert.fail; 14 | import static org.mockito.BDDMockito.given; 15 | import static org.mockito.Mockito.mock; 16 | 17 | /** 18 | * @author Tadaya Tsuyukubo 19 | */ 20 | public class QueryExecutionAssertTest { 21 | 22 | @Test 23 | public void testIsSuccess() { 24 | QueryExecution qe = mock(QueryExecution.class); 25 | given(qe.isSuccess()).willReturn(true); 26 | 27 | DataSourceAssertAssertions.assertThat(qe).isSuccess(); 28 | 29 | try { 30 | DataSourceAssertAssertions.assertThat(qe).isFailure(); 31 | fail("asserts should fail"); 32 | } catch (AssertionError e) { 33 | assertThat(e).hasMessage("\nExpecting: but was: \n"); 34 | } 35 | 36 | } 37 | 38 | @Test 39 | public void testIsFailure() { 40 | QueryExecution qe = mock(QueryExecution.class); 41 | given(qe.isSuccess()).willReturn(false); 42 | 43 | DataSourceAssertAssertions.assertThat(qe).isFailure(); 44 | 45 | try { 46 | DataSourceAssertAssertions.assertThat(qe).isSuccess(); 47 | fail("asserts should fail"); 48 | } catch (AssertionError e) { 49 | assertThat(e).hasMessage("\nExpecting: but was: \n"); 50 | } 51 | } 52 | 53 | @Test 54 | public void testIsBatch() { 55 | // batch=true 56 | QueryExecution qe = mock(QueryExecution.class); 57 | given(qe.isBatch()).willReturn(true); 58 | 59 | DataSourceAssertAssertions.assertThat(qe).isBatch(); 60 | 61 | // batch=false 62 | qe = mock(QueryExecution.class); 63 | given(qe.isBatch()).willReturn(false); 64 | try { 65 | DataSourceAssertAssertions.assertThat(qe).isBatch(); 66 | fail("asserts should fail"); 67 | } catch (AssertionError e) { 68 | assertThat(e).hasMessage("\nExpecting: but was: \n"); 69 | } 70 | } 71 | 72 | @Test 73 | public void testIsStatement() { 74 | QueryExecution se = new StatementExecution(); 75 | QueryExecution sbe = new StatementBatchExecution(); 76 | QueryExecution pe = new PreparedExecution(); 77 | 78 | DataSourceAssertAssertions.assertThat(se).isStatement(); 79 | DataSourceAssertAssertions.assertThat(sbe).isBatchStatement(); 80 | DataSourceAssertAssertions.assertThat(se).isStatementOrBatchStatement(); 81 | DataSourceAssertAssertions.assertThat(sbe).isStatementOrBatchStatement(); 82 | 83 | try { 84 | DataSourceAssertAssertions.assertThat(pe).isStatement(); 85 | fail("asserts should fail"); 86 | } catch (AssertionError e) { 87 | assertThat(e).hasMessage("\nExpecting: but was: \n"); 88 | } 89 | try { 90 | DataSourceAssertAssertions.assertThat(pe).isBatchStatement(); 91 | fail("asserts should fail"); 92 | } catch (AssertionError e) { 93 | assertThat(e).hasMessage("\nExpecting: but was: \n"); 94 | } 95 | try { 96 | DataSourceAssertAssertions.assertThat(pe).isStatementOrBatchStatement(); 97 | fail("asserts should fail"); 98 | } catch (AssertionError e) { 99 | assertThat(e).hasMessage("\nExpecting: but was: \n"); 100 | } 101 | } 102 | 103 | @Test 104 | public void testIsPrepared() { 105 | QueryExecution pe = new PreparedExecution(); 106 | QueryExecution pbe = new PreparedBatchExecution(); 107 | QueryExecution se = new StatementExecution(); 108 | 109 | DataSourceAssertAssertions.assertThat(pe).isPrepared(); 110 | DataSourceAssertAssertions.assertThat(pbe).isBatchPrepared(); 111 | DataSourceAssertAssertions.assertThat(pe).isPreparedOrBatchPrepared(); 112 | DataSourceAssertAssertions.assertThat(pbe).isPreparedOrBatchPrepared(); 113 | 114 | try { 115 | DataSourceAssertAssertions.assertThat(se).isPrepared(); 116 | fail("asserts should fail"); 117 | } catch (AssertionError e) { 118 | assertThat(e).hasMessage("\nExpecting: but was: \n"); 119 | } 120 | try { 121 | DataSourceAssertAssertions.assertThat(se).isBatchPrepared(); 122 | fail("asserts should fail"); 123 | } catch (AssertionError e) { 124 | assertThat(e).hasMessage("\nExpecting: but was: \n"); 125 | } 126 | try { 127 | DataSourceAssertAssertions.assertThat(se).isPreparedOrBatchPrepared(); 128 | fail("asserts should fail"); 129 | } catch (AssertionError e) { 130 | assertThat(e).hasMessage("\nExpecting: but was: \n"); 131 | } 132 | } 133 | 134 | @Test 135 | public void testIsCallable() { 136 | QueryExecution ce = new CallableExecution(); 137 | QueryExecution cbe = new CallableBatchExecution(); 138 | QueryExecution se = new StatementExecution(); 139 | 140 | DataSourceAssertAssertions.assertThat(ce).isCallable(); 141 | DataSourceAssertAssertions.assertThat(cbe).isBatchCallable(); 142 | DataSourceAssertAssertions.assertThat(ce).isCallableOrBatchCallable(); 143 | DataSourceAssertAssertions.assertThat(cbe).isCallableOrBatchCallable(); 144 | 145 | try { 146 | DataSourceAssertAssertions.assertThat(se).isCallable(); 147 | fail("asserts should fail"); 148 | } catch (AssertionError e) { 149 | assertThat(e).hasMessage("\nExpecting: but was: \n"); 150 | } 151 | try { 152 | DataSourceAssertAssertions.assertThat(se).isBatchCallable(); 153 | fail("asserts should fail"); 154 | } catch (AssertionError e) { 155 | assertThat(e).hasMessage("\nExpecting: but was: \n"); 156 | } 157 | try { 158 | DataSourceAssertAssertions.assertThat(se).isCallableOrBatchCallable(); 159 | fail("asserts should fail"); 160 | } catch (AssertionError e) { 161 | assertThat(e).hasMessage("\nExpecting: but was: \n"); 162 | } 163 | } 164 | } 165 | -------------------------------------------------------------------------------- /src/test/java/net/ttddyy/dsproxy/asserts/assertj/StatementBatchExecutionAssertTest.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts.assertj; 2 | 3 | import net.ttddyy.dsproxy.QueryType; 4 | import net.ttddyy.dsproxy.asserts.StatementBatchExecution; 5 | import org.junit.Before; 6 | import org.junit.Test; 7 | 8 | import java.util.ArrayList; 9 | import java.util.Arrays; 10 | import java.util.List; 11 | 12 | import static org.assertj.core.api.Assertions.assertThat; 13 | import static org.assertj.core.api.Assertions.atIndex; 14 | import static org.junit.Assert.fail; 15 | import static org.mockito.BDDMockito.given; 16 | import static org.mockito.Mockito.mock; 17 | 18 | /** 19 | * @author Tadaya Tsuyukubo 20 | */ 21 | public class StatementBatchExecutionAssertTest { 22 | private StatementBatchExecution sbe; 23 | private StatementBatchExecutionAssert sbeAssert; 24 | 25 | @Before 26 | public void setUp() { 27 | this.sbe = new StatementBatchExecution(); 28 | this.sbeAssert = new StatementBatchExecutionAssert(this.sbe); 29 | } 30 | 31 | @Test 32 | public void testIsSuccess() { 33 | // success case 34 | this.sbe.setSuccess(true); 35 | this.sbeAssert.isSuccess(); 36 | 37 | // failure case 38 | this.sbe.setSuccess(false); 39 | try { 40 | this.sbeAssert.isSuccess(); 41 | fail("asserts should fail"); 42 | } catch (AssertionError e) { 43 | assertThat(e).hasMessage("\nExpecting: but was: \n"); 44 | } 45 | 46 | } 47 | 48 | @Test 49 | public void testIsFailure() { 50 | // success case 51 | this.sbe.setSuccess(false); 52 | this.sbeAssert.isFailure(); 53 | 54 | // failure case 55 | this.sbe.setSuccess(true); 56 | try { 57 | this.sbeAssert.isFailure(); 58 | fail("asserts should fail"); 59 | } catch (AssertionError e) { 60 | assertThat(e).hasMessage("\nExpecting: but was: \n"); 61 | } 62 | } 63 | 64 | @Test 65 | public void testHasBatchSize() { 66 | List entries = new ArrayList<>(); 67 | entries.addAll(Arrays.asList("a", "b", "c")); 68 | 69 | StatementBatchExecution sbe = mock(StatementBatchExecution.class); 70 | given(sbe.getQueries()).willReturn(entries); 71 | 72 | DataSourceAssertAssertions.assertThat(sbe).hasBatchSize(3); 73 | 74 | try { 75 | DataSourceAssertAssertions.assertThat(sbe).hasBatchSize(1); 76 | fail("exception should be thrown"); 77 | } catch (AssertionError e) { 78 | assertThat(e).hasMessage("\nExpected batch size:<1> but was:<3> in batch statement executions\n"); 79 | } 80 | } 81 | 82 | @Test 83 | public void testQueries() { 84 | StatementBatchExecution sbe = new StatementBatchExecution(); 85 | sbe.getQueries().add("foo"); 86 | sbe.getQueries().add("bar"); 87 | sbe.getQueries().add("baz"); 88 | 89 | DataSourceAssertAssertions.assertThat(sbe).queries().contains("bar"); 90 | 91 | try { 92 | DataSourceAssertAssertions.assertThat(sbe).queries().contains("WRONG"); 93 | fail("exception should be thrown"); 94 | } catch (AssertionError e) { 95 | } 96 | } 97 | 98 | @Test 99 | public void testQuery() { 100 | StatementBatchExecution sbe = new StatementBatchExecution(); 101 | sbe.getQueries().add("foo"); 102 | sbe.getQueries().add("bar"); 103 | sbe.getQueries().add("baz"); 104 | 105 | DataSourceAssertAssertions.assertThat(sbe).query(1).isEqualTo("bar"); 106 | 107 | try { 108 | DataSourceAssertAssertions.assertThat(sbe).query(3); 109 | fail("exception should be thrown"); 110 | } catch (Throwable e) { 111 | assertThat(e).isInstanceOf(IndexOutOfBoundsException.class); 112 | } 113 | } 114 | 115 | @Test 116 | public void testContains() { 117 | StatementBatchExecution sbe = new StatementBatchExecution(); 118 | sbe.getQueries().add("SELECT"); 119 | sbe.getQueries().add("INSERT"); 120 | sbe.getQueries().add("SELECT"); 121 | 122 | DataSourceAssertAssertions.assertThat(sbe).contains(QueryType.SELECT, 0); 123 | DataSourceAssertAssertions.assertThat(sbe).contains(QueryType.INSERT, 1); 124 | DataSourceAssertAssertions.assertThat(sbe).contains(QueryType.SELECT, atIndex(2)); 125 | 126 | // wrong type 127 | try { 128 | DataSourceAssertAssertions.assertThat(sbe).contains(QueryType.DELETE, 0); 129 | fail("exception should be thrown"); 130 | } catch (AssertionError e) { 131 | assertThat(e).hasMessage("\nExpected query type: but was:\n"); 99 | } 100 | } 101 | 102 | } 103 | -------------------------------------------------------------------------------- /src/test/java/net/ttddyy/dsproxy/asserts/hamcrest/BatchParameterHolderAssertionsTest.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts.hamcrest; 2 | 3 | import net.ttddyy.dsproxy.asserts.BatchExecutionEntry; 4 | import net.ttddyy.dsproxy.asserts.BatchParameterHolder; 5 | import net.ttddyy.dsproxy.asserts.ParameterByIndexHolder; 6 | import org.junit.Assert; 7 | import org.junit.Test; 8 | 9 | import java.util.ArrayList; 10 | import java.util.Arrays; 11 | import java.util.List; 12 | 13 | import static net.ttddyy.dsproxy.asserts.hamcrest.DataSourceAssertMatchers.paramIndexes; 14 | import static org.assertj.core.api.Assertions.assertThat; 15 | import static org.hamcrest.Matchers.hasItem; 16 | import static org.junit.Assert.fail; 17 | import static org.mockito.BDDMockito.given; 18 | import static org.mockito.Mockito.mock; 19 | import static org.mockito.Mockito.withSettings; 20 | 21 | /** 22 | * @author Tadaya Tsuyukubo 23 | * @since 1.0 24 | */ 25 | public class BatchParameterHolderAssertionsTest { 26 | 27 | @Test 28 | public void testBatchSize() { 29 | BatchExecutionEntry entry = mock(BatchExecutionEntry.class); 30 | 31 | ArrayList entries = new ArrayList<>(); 32 | entries.add(entry); 33 | 34 | BatchParameterHolder holder = mock(BatchParameterHolder.class); 35 | given(holder.getBatchExecutionEntries()).willReturn(entries); 36 | 37 | Assert.assertThat(holder, BatchParameterHolderAssertions.batchSize(1)); 38 | } 39 | 40 | @Test 41 | public void testBatchSizeFailure() { 42 | BatchParameterHolder holder = mock(BatchParameterHolder.class); 43 | given(holder.getBatchExecutionEntries()).willReturn(new ArrayList()); // empty list 44 | 45 | 46 | try { 47 | Assert.assertThat(holder, BatchParameterHolderAssertions.batchSize(1)); 48 | fail("exception should be thrown"); 49 | } catch (AssertionError e) { 50 | assertThat(e).hasMessage("\nExpected: batchSize <1>\n but: batchSize was <0>"); 51 | } 52 | } 53 | 54 | @Test 55 | public void testBatch() { 56 | ParameterByIndexHolder entry = mock(ParameterByIndexHolder.class, withSettings().extraInterfaces(BatchExecutionEntry.class)); 57 | given(entry.getParamIndexes()).willReturn(Arrays.asList(100)); 58 | List entries = Arrays.asList((BatchExecutionEntry) entry); 59 | 60 | BatchParameterHolder holder = mock(BatchParameterHolder.class); 61 | given(holder.getBatchExecutionEntries()).willReturn(entries); 62 | 63 | 64 | Assert.assertThat(holder, BatchParameterHolderAssertions.batch(0, paramIndexes(hasItem(100)))); 65 | } 66 | 67 | @Test 68 | public void testBatchOutOfIndex() { 69 | BatchParameterHolder holder = mock(BatchParameterHolder.class); 70 | given(holder.getBatchExecutionEntries()).willReturn(new ArrayList()); // empty list 71 | 72 | 73 | try { 74 | Assert.assertThat(holder, BatchParameterHolderAssertions.batch(10, paramIndexes(hasItem(100)))); 75 | fail("exception should be thrown"); 76 | } catch (AssertionError e) { 77 | assertThat(e).hasMessage("\nExpected: batch[10] exists\n but: batch[] size was 0"); 78 | } 79 | 80 | } 81 | 82 | @Test 83 | public void testBatchUnmatchMessage() { 84 | ParameterByIndexHolder entry = mock(ParameterByIndexHolder.class, withSettings().extraInterfaces(BatchExecutionEntry.class)); 85 | given(entry.getParamIndexes()).willReturn(Arrays.asList(100)); 86 | List entries = Arrays.asList((BatchExecutionEntry) entry); 87 | 88 | BatchParameterHolder holder = mock(BatchParameterHolder.class); 89 | given(holder.getBatchExecutionEntries()).willReturn(entries); 90 | 91 | 92 | try { 93 | Assert.assertThat(holder, BatchParameterHolderAssertions.batch(0, paramIndexes(hasItem(50)))); 94 | fail("exception should be thrown"); 95 | } catch (AssertionError e) { 96 | assertThat(e).hasMessage("\nExpected: batch[0] parameter indexes as a collection containing <50>\n but: batch[0] mismatches were: [was <100>]"); 97 | } 98 | 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /src/test/java/net/ttddyy/dsproxy/asserts/hamcrest/CallableExecutionTest.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts.hamcrest; 2 | 3 | import net.ttddyy.dsproxy.asserts.CallableExecution; 4 | import org.hamcrest.Matcher; 5 | import org.junit.Test; 6 | 7 | import static net.ttddyy.dsproxy.asserts.ParameterKeyValueUtils.createSetParam; 8 | import static net.ttddyy.dsproxy.asserts.hamcrest.DataSourceAssertMatchers.*; 9 | import static org.hamcrest.Matchers.hasEntry; 10 | import static org.hamcrest.Matchers.hasItem; 11 | import static org.hamcrest.Matchers.hasSize; 12 | import static org.hamcrest.Matchers.is; 13 | import static org.hamcrest.Matchers.startsWith; 14 | import static org.junit.Assert.assertThat; 15 | 16 | /** 17 | * @author Tadaya Tsuyukubo 18 | * @since 1.0 19 | */ 20 | public class CallableExecutionTest { 21 | 22 | @Test 23 | public void testQuery() { 24 | CallableExecution ce = new CallableExecution(); 25 | ce.setQuery("foo"); 26 | 27 | assertThat(ce, query(is("foo"))); 28 | assertThat(ce, query(startsWith("fo"))); 29 | assertThat(ce.getQuery(), is("foo")); 30 | } 31 | 32 | @Test 33 | public void testParamsByName() { 34 | CallableExecution ce = new CallableExecution(); 35 | ce.getAllParameters().add(createSetParam("foo", "FOO")); 36 | ce.getAllParameters().add(createSetParam("bar", "BAR")); 37 | ce.getAllParameters().add(createSetParam("baz", "BAZ")); 38 | ce.getAllParameters().add(createSetParam("number", 100)); 39 | assertThat(ce, paramsByName(hasEntry("bar", (Object) "BAR"))); 40 | assertThat(ce, paramsByName(hasEntry("number", (Object) 100))); 41 | } 42 | 43 | @Test 44 | public void testParamsByIndex() { 45 | CallableExecution ce = new CallableExecution(); 46 | ce.getAllParameters().add(createSetParam(1, "FOO")); 47 | ce.getAllParameters().add(createSetParam(2, "BAR")); 48 | ce.getAllParameters().add(createSetParam(3, "BAZ")); 49 | ce.getAllParameters().add(createSetParam(10, 100)); 50 | assertThat(ce, paramsByIndex(hasEntry(2, (Object) "BAR"))); 51 | assertThat(ce, paramsByIndex(hasEntry(10, (Object) 100))); 52 | } 53 | 54 | 55 | @Test 56 | public void testParamNames() { 57 | CallableExecution ce = new CallableExecution(); 58 | ce.getAllParameters().add(createSetParam("foo", "FOO")); 59 | ce.getAllParameters().add(createSetParam("bar", "BAR")); 60 | ce.getAllParameters().add(createSetParam("baz", "BAZ")); 61 | assertThat(ce, paramNames(hasItem("foo"))); 62 | assertThat(ce, paramNames(hasSize(3))); 63 | } 64 | 65 | @Test 66 | public void testParamIndexes() { 67 | CallableExecution ce = new CallableExecution(); 68 | ce.getAllParameters().add(createSetParam(1, "FOO")); 69 | ce.getAllParameters().add(createSetParam(2, "BAR")); 70 | ce.getAllParameters().add(createSetParam(3, "BAZ")); 71 | assertThat(ce, paramIndexes(hasItem(1))); 72 | assertThat(ce, paramIndexes(hasSize(3))); 73 | } 74 | 75 | @Test 76 | @SuppressWarnings("unchecked") 77 | public void testParamValueByName() { 78 | CallableExecution ce = new CallableExecution(); 79 | ce.getAllParameters().add(createSetParam("foo", "FOO")); 80 | ce.getAllParameters().add(createSetParam("number", 100)); 81 | 82 | assertThat(ce, param("foo", is((Object) "FOO"))); 83 | 84 | assertThat(ce, param("foo", (Matcher) startsWith("FOO"))); 85 | assertThat(ce, param("number", is((Object) 100))); 86 | } 87 | 88 | @Test 89 | @SuppressWarnings("unchecked") 90 | public void testParamValueByIndex() { 91 | CallableExecution ce = new CallableExecution(); 92 | ce.getAllParameters().add(createSetParam(1, "FOO")); 93 | ce.getAllParameters().add(createSetParam(2, 100)); 94 | 95 | assertThat(ce, param(1, is((Object) "FOO"))); 96 | 97 | assertThat(ce, param(1, (Matcher) startsWith("FOO"))); 98 | assertThat(ce, param(2, is((Object) 100))); 99 | } 100 | // 101 | // @Test 102 | // public void testParamValueWithClass() { 103 | // PreparedExecution pe = new PreparedExecution(); 104 | // pe.getSetParams().put("foo", "FOO"); 105 | // pe.getSetParams().put("number", 100); 106 | // 107 | // assertThat(pe, paramValue("foo", String.class, is("FOO"))); 108 | // assertThat(pe, paramValue("foo", String.class, startsWith("FOO"))); 109 | // assertThat(pe, paramValue("number", Integer.class, is(100))); 110 | // } 111 | 112 | } 113 | -------------------------------------------------------------------------------- /src/test/java/net/ttddyy/dsproxy/asserts/hamcrest/CompositeMatcherTest.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts.hamcrest; 2 | 3 | import org.hamcrest.Description; 4 | import org.hamcrest.Matcher; 5 | import org.junit.Assert; 6 | import org.junit.Test; 7 | 8 | import static org.assertj.core.api.Assertions.assertThat; 9 | import static org.hamcrest.Matchers.startsWith; 10 | import static org.junit.Assert.fail; 11 | 12 | /** 13 | * @author Tadaya Tsuyukubo 14 | * @since 1.0 15 | */ 16 | public class CompositeMatcherTest { 17 | 18 | @Test 19 | @SuppressWarnings("unchecked") 20 | public void whenWrongExpectedTypeForCompositeMatcher() { 21 | Matcher subMatcher = startsWith("foo"); 22 | 23 | CompositeMatcher matcher = new CompositeMatcher(subMatcher) { 24 | @Override 25 | public String getValue(String actual) { 26 | return null; 27 | } 28 | 29 | @Override 30 | public String getSubMatcherFailureDescriptionPrefix() { 31 | return "pre "; 32 | } 33 | }; 34 | 35 | 36 | try { 37 | Assert.assertThat(100, matcher); 38 | fail("validation should fail"); 39 | } catch (Throwable e) { 40 | assertThat(e).hasMessageContaining("Expected: java.lang.String\n but: was a java.lang.Integer (<100>)"); 41 | } 42 | } 43 | 44 | @Test 45 | @SuppressWarnings("unchecked") 46 | public void whenWrongExpectedTypeForSubMatcher() { 47 | Matcher subMatcher = startsWith("foo"); 48 | 49 | CompositeMatcher matcher = new CompositeMatcher(subMatcher) { 50 | @Override 51 | public Object getValue(String actual) { 52 | return 100; // return int instead of String 53 | } 54 | 55 | @Override 56 | public String getSubMatcherFailureDescriptionPrefix() { 57 | return "pre "; 58 | } 59 | }; 60 | 61 | 62 | try { 63 | Assert.assertThat("FOO", matcher); 64 | fail("validation should fail"); 65 | } catch (Throwable e) { 66 | assertThat(e).hasMessageContaining("Expected: pre a string starting with \"foo\"\n but: pre was a java.lang.Integer (<100>)"); 67 | } 68 | } 69 | 70 | @Test 71 | public void whenValidationByCompositeMatcherFailed() { 72 | Matcher subMatcher = startsWith("foo"); 73 | 74 | CompositeMatcher matcher = new CompositeMatcher(subMatcher) { 75 | @Override 76 | public String getValue(String actual) { 77 | return "foo"; 78 | } 79 | 80 | @Override 81 | protected boolean validateByThisMatcher(String item, Description expected, Description actual) { 82 | assertThat(item).isEqualTo("AAA"); 83 | expected.appendText("expected"); 84 | actual.appendText("actual"); 85 | return false; 86 | } 87 | 88 | @Override 89 | public String getSubMatcherFailureDescriptionPrefix() { 90 | return "pre "; 91 | } 92 | }; 93 | 94 | 95 | try { 96 | Assert.assertThat("AAA", matcher); 97 | fail("validateByThisMatcher method should fail"); 98 | } catch (Throwable e) { 99 | assertThat(e).hasMessageContaining("Expected: expected\n but: actual"); 100 | } 101 | } 102 | 103 | @Test 104 | public void whenExpectationBySubMatcherFailed() { 105 | Matcher subMatcher = startsWith("foo"); 106 | 107 | CompositeMatcher matcher = new CompositeMatcher(subMatcher) { 108 | @Override 109 | public String getValue(String actual) { 110 | return "FOO"; 111 | } 112 | 113 | @Override 114 | public String getSubMatcherFailureDescriptionPrefix() { 115 | return "pre "; 116 | } 117 | }; 118 | 119 | 120 | try { 121 | Assert.assertThat("AAA", matcher); 122 | fail("validateByThisMatcher method should fail"); 123 | } catch (Throwable e) { 124 | assertThat(e).hasMessageContaining("Expected: pre a string starting with \"foo\"\n but: pre was \"FOO\""); 125 | } 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /src/test/java/net/ttddyy/dsproxy/asserts/hamcrest/ExecutionTypeMatcherTest.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts.hamcrest; 2 | 3 | import net.ttddyy.dsproxy.asserts.StatementExecution; 4 | import org.junit.Assert; 5 | import org.junit.Test; 6 | 7 | import static org.assertj.core.api.Assertions.assertThat; 8 | import static org.junit.Assert.fail; 9 | 10 | /** 11 | * @author Tadaya Tsuyukubo 12 | * @since 1.0 13 | */ 14 | public class ExecutionTypeMatcherTest { 15 | 16 | @Test 17 | public void testMatch() { 18 | StatementExecution se = new StatementExecution(); 19 | ExecutionTypeMatcher matcher = new ExecutionTypeMatcher(ExecutionType.IS_STATEMENT); 20 | assertThat(matcher.matches(se)).isTrue(); 21 | } 22 | 23 | @Test 24 | public void testUnmatchMessage() { 25 | StatementExecution se = new StatementExecution(); 26 | ExecutionTypeMatcher matcher = new ExecutionTypeMatcher(ExecutionType.IS_CALLABLE); 27 | try { 28 | Assert.assertThat(se, matcher); 29 | fail("asserts should fail"); 30 | } catch (AssertionError e) { 31 | assertThat(e).hasMessage("\nExpected: callable\n but: was statement"); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/test/java/net/ttddyy/dsproxy/asserts/hamcrest/PreparedBatchExecutionMatcherTest.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts.hamcrest; 2 | 3 | import net.ttddyy.dsproxy.asserts.PreparedBatchExecution; 4 | import net.ttddyy.dsproxy.asserts.PreparedBatchExecutionEntry; 5 | import org.hamcrest.Matcher; 6 | import org.junit.Test; 7 | 8 | import static net.ttddyy.dsproxy.asserts.ParameterKeyValueUtils.createSetParam; 9 | import static net.ttddyy.dsproxy.asserts.hamcrest.DataSourceAssertMatchers.batch; 10 | import static net.ttddyy.dsproxy.asserts.hamcrest.DataSourceAssertMatchers.batchSize; 11 | import static net.ttddyy.dsproxy.asserts.hamcrest.DataSourceAssertMatchers.param; 12 | import static net.ttddyy.dsproxy.asserts.hamcrest.DataSourceAssertMatchers.paramAsInteger; 13 | import static net.ttddyy.dsproxy.asserts.hamcrest.DataSourceAssertMatchers.paramAsString; 14 | import static net.ttddyy.dsproxy.asserts.hamcrest.DataSourceAssertMatchers.paramIndexes; 15 | import static net.ttddyy.dsproxy.asserts.hamcrest.DataSourceAssertMatchers.paramsByIndex; 16 | import static net.ttddyy.dsproxy.asserts.hamcrest.DataSourceAssertMatchers.query; 17 | import static org.hamcrest.Matchers.hasEntry; 18 | import static org.hamcrest.Matchers.hasItem; 19 | import static org.hamcrest.Matchers.hasItems; 20 | import static org.hamcrest.Matchers.is; 21 | import static org.hamcrest.Matchers.startsWith; 22 | import static org.junit.Assert.assertThat; 23 | 24 | /** 25 | * @author Tadaya Tsuyukubo 26 | * @since 1.0 27 | */ 28 | public class PreparedBatchExecutionMatcherTest { 29 | 30 | @Test 31 | public void testQuery() { 32 | PreparedBatchExecution pbe = new PreparedBatchExecution(); 33 | pbe.setQuery("foo"); 34 | 35 | assertThat(pbe, query(is("foo"))); 36 | assertThat(pbe, query(startsWith("fo"))); 37 | assertThat(pbe.getQuery(), is("foo")); 38 | } 39 | 40 | @Test 41 | public void testBatchSize() { 42 | PreparedBatchExecutionEntry entry1 = new PreparedBatchExecutionEntry(); 43 | entry1.getAllParameters().add(createSetParam(10, "FOO")); 44 | entry1.getAllParameters().add(createSetParam(11, "BAR")); 45 | 46 | PreparedBatchExecutionEntry entry2 = new PreparedBatchExecutionEntry(); 47 | entry2.getAllParameters().add(createSetParam(20, "FOO")); 48 | entry2.getAllParameters().add(createSetParam(21, "BAR")); 49 | 50 | PreparedBatchExecution pbe = new PreparedBatchExecution(); 51 | pbe.addBatchExecutionEntry(entry1); 52 | pbe.addBatchExecutionEntry(entry2); 53 | 54 | assertThat(pbe, batchSize(2)); 55 | } 56 | 57 | @Test 58 | @SuppressWarnings("unchecked") 59 | public void testBatch() { 60 | 61 | PreparedBatchExecutionEntry entry = new PreparedBatchExecutionEntry(); 62 | entry.getAllParameters().add(createSetParam(1, "FOO")); 63 | entry.getAllParameters().add(createSetParam(2, "BAR")); 64 | entry.getAllParameters().add(createSetParam(10, 100)); 65 | 66 | PreparedBatchExecution pbe = new PreparedBatchExecution(); 67 | pbe.addBatchExecutionEntry(entry); 68 | 69 | assertThat(pbe, batch(0, paramsByIndex(hasEntry(2, (Object) "BAR")))); 70 | assertThat(pbe, batch(0, paramsByIndex(hasEntry(10, (Object) 100)))); 71 | assertThat(pbe, batch(0, paramIndexes(hasItem(1)))); 72 | assertThat(pbe, batch(0, paramIndexes(hasItems(1, 2)))); 73 | 74 | assertThat(pbe, batch(0, param(1, is((Object) "FOO")))); 75 | assertThat(pbe, batch(0, param(1, (Matcher) startsWith("FOO")))); 76 | assertThat(pbe, batch(0, param(10, is((Object) 100)))); 77 | 78 | assertThat(pbe, batch(0, param(1, String.class, is("FOO")))); 79 | assertThat(pbe, batch(0, param(1, String.class, startsWith("FOO")))); 80 | assertThat(pbe, batch(0, param(10, Integer.class, is(100)))); 81 | 82 | } 83 | 84 | @Test 85 | @SuppressWarnings("unchecked") 86 | public void testBatchByIndex() { 87 | 88 | PreparedBatchExecutionEntry entry = new PreparedBatchExecutionEntry(); 89 | entry.getAllParameters().add(createSetParam(1, "FOO")); 90 | entry.getAllParameters().add(createSetParam(2, "BAR")); 91 | entry.getAllParameters().add(createSetParam(3, 100)); 92 | 93 | 94 | PreparedBatchExecution pbe = new PreparedBatchExecution(); 95 | pbe.addBatchExecutionEntry(entry); 96 | 97 | assertThat(pbe, batch(0, paramsByIndex(hasEntry(2, (Object) "BAR")))); 98 | assertThat(pbe, batch(0, paramsByIndex(hasEntry(3, (Object) 100)))); 99 | assertThat(pbe, batch(0, paramIndexes(hasItem(1)))); 100 | assertThat(pbe, batch(0, paramIndexes(hasItems(1, 2)))); 101 | assertThat(pbe, batch(0, paramIndexes(1))); 102 | assertThat(pbe, batch(0, paramIndexes(1, 2))); 103 | 104 | assertThat(pbe, batch(0, param(1, is((Object) "FOO")))); 105 | assertThat(pbe, batch(0, param(1, (Matcher) startsWith("FOO")))); 106 | assertThat(pbe, batch(0, param(3, is((Object) 100)))); 107 | 108 | assertThat(pbe, batch(0, param(1, String.class, is("FOO")))); 109 | assertThat(pbe, batch(0, param(1, String.class, startsWith("FOO")))); 110 | assertThat(pbe, batch(0, param(3, Integer.class, is(100)))); 111 | 112 | assertThat(pbe, batch(0, paramAsString(1, is("FOO")))); 113 | assertThat(pbe, batch(0, paramAsInteger(3, is(100)))); 114 | 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /src/test/java/net/ttddyy/dsproxy/asserts/hamcrest/PreparedExecutionTest.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts.hamcrest; 2 | 3 | import net.ttddyy.dsproxy.asserts.PreparedExecution; 4 | import org.hamcrest.Matcher; 5 | import org.junit.Test; 6 | 7 | import static net.ttddyy.dsproxy.asserts.ParameterKeyValueUtils.createSetParam; 8 | import static net.ttddyy.dsproxy.asserts.hamcrest.DataSourceAssertMatchers.param; 9 | import static net.ttddyy.dsproxy.asserts.hamcrest.DataSourceAssertMatchers.paramIndexes; 10 | import static net.ttddyy.dsproxy.asserts.hamcrest.DataSourceAssertMatchers.paramsByIndex; 11 | import static net.ttddyy.dsproxy.asserts.hamcrest.DataSourceAssertMatchers.query; 12 | import static org.hamcrest.Matchers.hasEntry; 13 | import static org.hamcrest.Matchers.hasItem; 14 | import static org.hamcrest.Matchers.hasSize; 15 | import static org.hamcrest.Matchers.is; 16 | import static org.hamcrest.Matchers.startsWith; 17 | import static org.junit.Assert.assertThat; 18 | 19 | /** 20 | * @author Tadaya Tsuyukubo 21 | * @since 1.0 22 | */ 23 | public class PreparedExecutionTest { 24 | 25 | @Test 26 | public void testQuery() { 27 | PreparedExecution pe = new PreparedExecution(); 28 | pe.setQuery("foo"); 29 | 30 | assertThat(pe, query(is("foo"))); 31 | assertThat(pe, query(startsWith("fo"))); 32 | assertThat(pe.getQuery(), is("foo")); 33 | } 34 | 35 | @Test 36 | public void testParams() { 37 | PreparedExecution pe = new PreparedExecution(); 38 | pe.getAllParameters().add(createSetParam(1, "foo")); 39 | pe.getAllParameters().add(createSetParam(2, "bar")); 40 | pe.getAllParameters().add(createSetParam(3, "baz")); 41 | pe.getAllParameters().add(createSetParam(4, 100)); 42 | assertThat(pe, paramsByIndex(hasEntry(2, (Object) "bar"))); 43 | assertThat(pe, paramsByIndex(hasEntry(4, (Object) 100))); 44 | } 45 | 46 | @Test 47 | public void testParamIndexes() { 48 | PreparedExecution pe = new PreparedExecution(); 49 | pe.getAllParameters().add(createSetParam(1, "foo")); 50 | pe.getAllParameters().add(createSetParam(2, "bar")); 51 | pe.getAllParameters().add(createSetParam(3, "baz")); 52 | assertThat(pe, paramIndexes(hasItem(1))); 53 | assertThat(pe, paramIndexes(hasSize(3))); 54 | } 55 | 56 | @Test 57 | @SuppressWarnings("unchecked") 58 | public void testParamValue() { 59 | PreparedExecution pe = new PreparedExecution(); 60 | pe.getAllParameters().add(createSetParam(1, "foo")); 61 | pe.getAllParameters().add(createSetParam(100, 100)); 62 | 63 | assertThat(pe, param(1, is((Object) "foo"))); 64 | 65 | assertThat(pe, param(1, (Matcher) startsWith("foo"))); 66 | assertThat(pe, param(100, is((Object) 100))); 67 | } 68 | 69 | @Test 70 | public void testParamValueWithClass() { 71 | PreparedExecution pe = new PreparedExecution(); 72 | pe.getAllParameters().add(createSetParam(1, "foo")); 73 | pe.getAllParameters().add(createSetParam(100, 100)); 74 | 75 | assertThat(pe, param(1, String.class, is("foo"))); 76 | assertThat(pe, param(1, String.class, startsWith("foo"))); 77 | assertThat(pe, param(100, Integer.class, is(100))); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/test/java/net/ttddyy/dsproxy/asserts/hamcrest/QueriesHolderAssertionsTest.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts.hamcrest; 2 | 3 | import net.ttddyy.dsproxy.asserts.StatementBatchExecution; 4 | import org.junit.Assert; 5 | import org.junit.Test; 6 | 7 | import static net.ttddyy.dsproxy.asserts.hamcrest.QueriesHolderAssertions.queries; 8 | import static net.ttddyy.dsproxy.asserts.hamcrest.QueriesHolderAssertions.queryTypes; 9 | import static net.ttddyy.dsproxy.asserts.hamcrest.DataSourceAssertMatchers.delete; 10 | import static net.ttddyy.dsproxy.asserts.hamcrest.DataSourceAssertMatchers.insert; 11 | import static net.ttddyy.dsproxy.asserts.hamcrest.DataSourceAssertMatchers.select; 12 | import static net.ttddyy.dsproxy.asserts.hamcrest.DataSourceAssertMatchers.update; 13 | import static org.assertj.core.api.Assertions.assertThat; 14 | import static org.hamcrest.Matchers.hasItem; 15 | import static org.hamcrest.Matchers.hasItems; 16 | import static org.hamcrest.Matchers.hasSize; 17 | import static org.hamcrest.Matchers.is; 18 | import static org.hamcrest.Matchers.startsWith; 19 | import static org.junit.Assert.fail; 20 | 21 | /** 22 | * @author Tadaya Tsuyukubo 23 | * @since 1.0 24 | */ 25 | public class QueriesHolderAssertionsTest { 26 | 27 | 28 | @Test 29 | public void queriesWithIndex() { 30 | StatementBatchExecution sbe = new StatementBatchExecution(); 31 | sbe.getQueries().add("foo"); 32 | sbe.getQueries().add("bar"); 33 | sbe.getQueries().add("baz"); 34 | 35 | Assert.assertThat(sbe, queries(0, is("foo"))); 36 | Assert.assertThat(sbe, queries(1, is("bar"))); 37 | Assert.assertThat(sbe, queries(2, is("baz"))); 38 | 39 | Assert.assertThat(sbe, queries(0, startsWith("f"))); 40 | } 41 | 42 | @Test 43 | public void queriesWithIndexWhenIndexIsOutOfBound() { 44 | StatementBatchExecution sbe = new StatementBatchExecution(); 45 | sbe.getQueries().add("foo"); 46 | sbe.getQueries().add("bar"); 47 | sbe.getQueries().add("baz"); 48 | 49 | try { 50 | Assert.assertThat(sbe, queries(100, is("foo"))); 51 | fail("asserts should fail"); 52 | } catch (AssertionError e) { 53 | assertThat(e).hasMessage("\nExpected: queries[100] exists\n but: queries[] size was 3"); 54 | } 55 | } 56 | 57 | @Test 58 | public void queriesWithIndexWhenExpectationMismatch() { 59 | StatementBatchExecution sbe = new StatementBatchExecution(); 60 | sbe.getQueries().add("foo"); 61 | 62 | try { 63 | Assert.assertThat(sbe, queries(0, is("FOO"))); 64 | fail("asserts should fail"); 65 | } catch (AssertionError e) { 66 | assertThat(e).hasMessage("\nExpected: queries[0] is \"FOO\"\n but: queries[0] was \"foo\""); 67 | } 68 | } 69 | 70 | @Test 71 | @SuppressWarnings("unchecked") 72 | public void queriesWithCollectionMatcher() { 73 | StatementBatchExecution sbe = new StatementBatchExecution(); 74 | sbe.getQueries().add("foo"); 75 | sbe.getQueries().add("bar"); 76 | sbe.getQueries().add("baz"); 77 | 78 | Assert.assertThat(sbe, queries(hasItem("foo"))); 79 | Assert.assertThat(sbe, queries(hasItems("foo", "bar"))); 80 | Assert.assertThat(sbe, queries(hasItems(startsWith("f"), is("bar")))); 81 | 82 | Assert.assertThat(sbe, queries(hasSize(3))); 83 | } 84 | 85 | @Test 86 | public void queriesWithCollectionWhenExpectationMismatch() { 87 | StatementBatchExecution sbe = new StatementBatchExecution(); 88 | sbe.getQueries().add("foo"); 89 | 90 | try { 91 | Assert.assertThat(sbe, queries(hasItem("FOO"))); 92 | } catch (AssertionError e) { 93 | assertThat(e).hasMessage("\nExpected: queries[] a collection containing \"FOO\"\n but: queries[] mismatches were: [was \"foo\"]"); 94 | } 95 | } 96 | 97 | 98 | @Test 99 | public void queryTypesWithIndex() { 100 | StatementBatchExecution sbe = new StatementBatchExecution(); 101 | sbe.getQueries().add("SELECT"); 102 | sbe.getQueries().add("INSERT"); 103 | sbe.getQueries().add("UPDATE"); 104 | sbe.getQueries().add("DELETE"); 105 | 106 | Assert.assertThat(sbe, queryTypes(0, select())); 107 | Assert.assertThat(sbe, queryTypes(1, insert())); 108 | Assert.assertThat(sbe, queryTypes(2, update())); 109 | Assert.assertThat(sbe, queryTypes(3, delete())); 110 | } 111 | 112 | @Test 113 | public void queryTypesWithIndexWhenExpectationMismatch() { 114 | StatementBatchExecution sbe = new StatementBatchExecution(); 115 | sbe.getQueries().add("SELECT"); 116 | 117 | try { 118 | Assert.assertThat(sbe, queryTypes(0, update())); 119 | fail("asserts should fail"); 120 | } catch (AssertionError e) { 121 | assertThat(e).hasMessage("\nExpected: queries[0] query type \"UPDATE\"\n but: queries[0] query type was \"SELECT\" (SELECT)"); 122 | } 123 | } 124 | 125 | @Test 126 | public void queryTypesWithIndexWhenOutOfIndex() { 127 | StatementBatchExecution sbe = new StatementBatchExecution(); 128 | sbe.getQueries().add("SELECT"); 129 | 130 | try { 131 | Assert.assertThat(sbe, queryTypes(100, select())); 132 | fail("asserts should fail"); 133 | } catch (AssertionError e) { 134 | assertThat(e).hasMessage("\nExpected: queries[100] exists\n but: queries[] size was 1"); 135 | } 136 | } 137 | 138 | } 139 | -------------------------------------------------------------------------------- /src/test/java/net/ttddyy/dsproxy/asserts/hamcrest/QueryExecutionAssertionsTest.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts.hamcrest; 2 | 3 | import net.ttddyy.dsproxy.asserts.CallableBatchExecution; 4 | import net.ttddyy.dsproxy.asserts.CallableExecution; 5 | import net.ttddyy.dsproxy.asserts.PreparedBatchExecution; 6 | import net.ttddyy.dsproxy.asserts.PreparedExecution; 7 | import net.ttddyy.dsproxy.asserts.QueryExecution; 8 | import net.ttddyy.dsproxy.asserts.StatementBatchExecution; 9 | import net.ttddyy.dsproxy.asserts.StatementExecution; 10 | import org.junit.Assert; 11 | import org.junit.Test; 12 | 13 | import static net.ttddyy.dsproxy.asserts.hamcrest.QueryExecutionAssertions.batch; 14 | import static net.ttddyy.dsproxy.asserts.hamcrest.QueryExecutionAssertions.batchCallable; 15 | import static net.ttddyy.dsproxy.asserts.hamcrest.QueryExecutionAssertions.batchPrepared; 16 | import static net.ttddyy.dsproxy.asserts.hamcrest.QueryExecutionAssertions.batchStatement; 17 | import static net.ttddyy.dsproxy.asserts.hamcrest.QueryExecutionAssertions.callable; 18 | import static net.ttddyy.dsproxy.asserts.hamcrest.QueryExecutionAssertions.callableOrBatchCallable; 19 | import static net.ttddyy.dsproxy.asserts.hamcrest.QueryExecutionAssertions.failure; 20 | import static net.ttddyy.dsproxy.asserts.hamcrest.QueryExecutionAssertions.prepared; 21 | import static net.ttddyy.dsproxy.asserts.hamcrest.QueryExecutionAssertions.preparedOrBatchPrepared; 22 | import static net.ttddyy.dsproxy.asserts.hamcrest.QueryExecutionAssertions.statement; 23 | import static net.ttddyy.dsproxy.asserts.hamcrest.QueryExecutionAssertions.statementOrBatchStatement; 24 | import static net.ttddyy.dsproxy.asserts.hamcrest.QueryExecutionAssertions.success; 25 | import static org.assertj.core.api.Assertions.assertThat; 26 | import static org.junit.Assert.fail; 27 | import static org.mockito.Mockito.mock; 28 | import static org.mockito.Mockito.when; 29 | 30 | /** 31 | * @author Tadaya Tsuyukubo 32 | * @since 1.0 33 | */ 34 | public class QueryExecutionAssertionsTest { 35 | 36 | @Test 37 | public void testSuccess() { 38 | QueryExecution qe = mock(QueryExecution.class); 39 | when(qe.isSuccess()).thenReturn(true); 40 | 41 | Assert.assertThat(qe, success()); 42 | } 43 | 44 | @Test 45 | public void testSuccessWithFailureMessage() { 46 | QueryExecution qe = mock(QueryExecution.class); 47 | when(qe.isSuccess()).thenReturn(false); 48 | 49 | 50 | try { 51 | Assert.assertThat(qe, success()); 52 | fail("asserts should fail"); 53 | } catch (AssertionError e) { 54 | assertThat(e).hasMessage("\nExpected: success\n but: was failure"); 55 | } 56 | } 57 | 58 | 59 | @Test 60 | public void testFailure() { 61 | QueryExecution qe = mock(QueryExecution.class); 62 | when(qe.isSuccess()).thenReturn(false); 63 | 64 | Assert.assertThat(qe, failure()); 65 | } 66 | 67 | @Test 68 | public void testFailWithFailureMessage() { 69 | QueryExecution qe = mock(QueryExecution.class); 70 | when(qe.isSuccess()).thenReturn(true); 71 | 72 | try { 73 | Assert.assertThat(qe, failure()); 74 | fail("asserts should fail"); 75 | } catch (AssertionError e) { 76 | assertThat(e).hasMessage("\nExpected: failure\n but: was success"); 77 | } 78 | 79 | } 80 | 81 | 82 | @Test 83 | public void testExecutions() { 84 | StatementExecution se = new StatementExecution(); 85 | StatementBatchExecution sbe = new StatementBatchExecution(); 86 | PreparedExecution pe = new PreparedExecution(); 87 | PreparedBatchExecution pbe = new PreparedBatchExecution(); 88 | CallableExecution ce = new CallableExecution(); 89 | CallableBatchExecution cbe = new CallableBatchExecution(); 90 | 91 | Assert.assertThat(se, statement()); 92 | Assert.assertThat(sbe, batchStatement()); 93 | Assert.assertThat(se, statementOrBatchStatement()); 94 | Assert.assertThat(sbe, statementOrBatchStatement()); 95 | 96 | Assert.assertThat(pe, prepared()); 97 | Assert.assertThat(pbe, batchPrepared()); 98 | Assert.assertThat(pe, preparedOrBatchPrepared()); 99 | Assert.assertThat(pbe, preparedOrBatchPrepared()); 100 | 101 | Assert.assertThat(ce, callable()); 102 | Assert.assertThat(cbe, batchCallable()); 103 | Assert.assertThat(ce, callableOrBatchCallable()); 104 | Assert.assertThat(cbe, callableOrBatchCallable()); 105 | 106 | Assert.assertThat(sbe, batch()); 107 | Assert.assertThat(pbe, batch()); 108 | Assert.assertThat(cbe, batch()); 109 | } 110 | 111 | } 112 | -------------------------------------------------------------------------------- /src/test/java/net/ttddyy/dsproxy/asserts/hamcrest/QueryHolderTest.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts.hamcrest; 2 | 3 | import net.ttddyy.dsproxy.QueryType; 4 | import net.ttddyy.dsproxy.asserts.QueryHolder; 5 | import org.junit.Assert; 6 | import org.junit.Test; 7 | 8 | import static net.ttddyy.dsproxy.asserts.hamcrest.QueryHolderAssertions.delete; 9 | import static net.ttddyy.dsproxy.asserts.hamcrest.QueryHolderAssertions.insert; 10 | import static net.ttddyy.dsproxy.asserts.hamcrest.QueryHolderAssertions.other; 11 | import static net.ttddyy.dsproxy.asserts.hamcrest.QueryHolderAssertions.query; 12 | import static net.ttddyy.dsproxy.asserts.hamcrest.QueryHolderAssertions.queryType; 13 | import static net.ttddyy.dsproxy.asserts.hamcrest.QueryHolderAssertions.select; 14 | import static net.ttddyy.dsproxy.asserts.hamcrest.QueryHolderAssertions.update; 15 | import static org.assertj.core.api.Assertions.assertThat; 16 | import static org.hamcrest.Matchers.is; 17 | import static org.hamcrest.Matchers.startsWith; 18 | import static org.junit.Assert.fail; 19 | import static org.mockito.BDDMockito.given; 20 | import static org.mockito.Mockito.mock; 21 | 22 | /** 23 | * @author Tadaya Tsuyukubo 24 | * @since 1.0 25 | */ 26 | public class QueryHolderTest { 27 | 28 | @Test 29 | public void testQuery() { 30 | QueryHolder queryHolder = mock(QueryHolder.class); 31 | given(queryHolder.getQuery()).willReturn("foo"); 32 | 33 | Assert.assertThat(queryHolder, query(is("foo"))); 34 | Assert.assertThat(queryHolder, query(startsWith("f"))); 35 | } 36 | 37 | @Test 38 | public void testQueryMismatch() { 39 | QueryHolder queryHolder = mock(QueryHolder.class); 40 | given(queryHolder.getQuery()).willReturn("foo"); 41 | 42 | try { 43 | Assert.assertThat(queryHolder, query(is("FOO"))); 44 | fail("asserts should fail"); 45 | } catch (AssertionError e) { 46 | assertThat(e).hasMessage("\nExpected: query is \"FOO\"\n but: query was \"foo\""); 47 | } 48 | } 49 | 50 | @Test 51 | public void testQueryType() { 52 | QueryHolder queryHolder = mock(QueryHolder.class); 53 | given(queryHolder.getQuery()).willReturn("SELECT"); 54 | Assert.assertThat(queryHolder, queryType(QueryType.SELECT)); 55 | 56 | queryHolder = mock(QueryHolder.class); 57 | given(queryHolder.getQuery()).willReturn("INSERT"); 58 | Assert.assertThat(queryHolder, queryType(QueryType.INSERT)); 59 | 60 | queryHolder = mock(QueryHolder.class); 61 | given(queryHolder.getQuery()).willReturn("UPDATE"); 62 | Assert.assertThat(queryHolder, queryType(QueryType.UPDATE)); 63 | queryHolder = mock(QueryHolder.class); 64 | given(queryHolder.getQuery()).willReturn("DELETE"); 65 | Assert.assertThat(queryHolder, queryType(QueryType.DELETE)); 66 | 67 | queryHolder = mock(QueryHolder.class); 68 | given(queryHolder.getQuery()).willReturn("OTHER"); 69 | Assert.assertThat(queryHolder, queryType(QueryType.OTHER)); 70 | } 71 | 72 | @Test 73 | public void testQueryTypeMismatch() { 74 | 75 | QueryHolder queryHolder = mock(QueryHolder.class); 76 | given(queryHolder.getQuery()).willReturn("insert into"); 77 | 78 | try { 79 | Assert.assertThat(queryHolder, queryType(QueryType.SELECT)); 80 | fail("asserts should fail"); 81 | } catch (AssertionError e) { 82 | assertThat(e).hasMessage("\nExpected: query type \"SELECT\"\n but: query type was \"INSERT\" (insert into)"); 83 | } 84 | 85 | } 86 | 87 | @Test 88 | public void testSpecificQueryType() { 89 | QueryHolder select = mock(QueryHolder.class); 90 | QueryHolder insert = mock(QueryHolder.class); 91 | QueryHolder update = mock(QueryHolder.class); 92 | QueryHolder delete = mock(QueryHolder.class); 93 | QueryHolder other = mock(QueryHolder.class); 94 | given(select.getQuery()).willReturn("SELECT..."); 95 | given(insert.getQuery()).willReturn("INSERT..."); 96 | given(update.getQuery()).willReturn("UPDATE..."); 97 | given(delete.getQuery()).willReturn("DELETE..."); 98 | given(other.getQuery()).willReturn("OTHER..."); 99 | 100 | Assert.assertThat(select, select()); 101 | Assert.assertThat(insert, insert()); 102 | Assert.assertThat(update, update()); 103 | Assert.assertThat(delete, delete()); 104 | Assert.assertThat(other, other()); 105 | } 106 | 107 | } 108 | -------------------------------------------------------------------------------- /src/test/java/net/ttddyy/dsproxy/asserts/hamcrest/SqlTypeMatcherTest.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts.hamcrest; 2 | 3 | import org.junit.Assert; 4 | import org.junit.Test; 5 | 6 | import java.sql.Types; 7 | 8 | import static org.assertj.core.api.Assertions.assertThat; 9 | import static org.junit.Assert.fail; 10 | 11 | 12 | /** 13 | * @author Tadaya Tsuyukubo 14 | * @since 1.0 15 | */ 16 | public class SqlTypeMatcherTest { 17 | 18 | @Test 19 | public void matcher() { 20 | SqlTypeMatcher matcher = new SqlTypeMatcher(Types.CHAR); 21 | Assert.assertThat(1, matcher); 22 | 23 | try { 24 | Assert.assertThat(Types.BIT, matcher); 25 | fail("AssertionError should be thrown"); 26 | } catch (AssertionError e) { 27 | assertThat(e).hasMessage("\nExpected: CHAR:1\n but: BIT:-7"); 28 | } 29 | } 30 | 31 | @Test 32 | public void messagePrefixAndSuffix(){ 33 | SqlTypeMatcher matcher = new SqlTypeMatcher(Types.DATE, "[PRE]", "[POST]"); 34 | try { 35 | Assert.assertThat(Types.TIME, matcher); 36 | fail("AssertionError should be thrown"); 37 | } catch (AssertionError e) { 38 | assertThat(e).hasMessage("\nExpected: [PRE]DATE:91[POST]\n but: [PRE]TIME:92[POST]"); 39 | } 40 | 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/test/java/net/ttddyy/dsproxy/asserts/hamcrest/StatementExecutionTest.java: -------------------------------------------------------------------------------- 1 | package net.ttddyy.dsproxy.asserts.hamcrest; 2 | 3 | import net.ttddyy.dsproxy.asserts.StatementExecution; 4 | import org.junit.Test; 5 | 6 | import static net.ttddyy.dsproxy.asserts.hamcrest.DataSourceAssertMatchers.query; 7 | import static org.hamcrest.Matchers.is; 8 | import static org.hamcrest.Matchers.startsWith; 9 | import static org.junit.Assert.assertThat; 10 | 11 | /** 12 | * @author Tadaya Tsuyukubo 13 | * @since 1.0 14 | */ 15 | public class StatementExecutionTest { 16 | 17 | @Test 18 | public void testQuery() { 19 | StatementExecution se = new StatementExecution(); 20 | se.setQuery("foo"); 21 | 22 | assertThat(se, query(is("foo"))); 23 | assertThat(se, query(startsWith("fo"))); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/test/resources/db/migration/V1__initialize_database.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE emp ( id INTEGER PRIMARY KEY, name VARCHAR(10) ); 2 | INSERT INTO emp ( id, name ) VALUES (1, 'foo'); 3 | INSERT INTO emp ( id, name ) VALUES (2, 'bar'); 4 | --------------------------------------------------------------------------------