-
-
Notifications
You must be signed in to change notification settings - Fork 399
Sample DB SQL Executor
If you are reading this wiki for the first time, this might take you around five minutes. Afterwards, it will take just a min only !
This is particularly useful where as part of your testing you are not satisfied only with the REST responses and you want to verify the DB changes has gone well or not. It's very easy to and sometimes it's a good practice to test this DB verification bit too.
Woking example repo is here to clone and run from your IDE : https://github.com/BeTheCodeWithYou/SpringBoot-ZeroCode-Integration
See this Wiki page for spinning up a docker container for a Postgres DB.
IP: localhost, Port:25432, Database name: postgres
db_host_url=jdbc:postgresql://localhost:35432/postgres
db_username=postgres
db_password=example
Docker DB logs below-
postgres=# CREATE TABLE employees (
postgres(# id bigint NOT NULL,
postgres(# name character varying(10) NOT NULL
postgres(# );
CREATE TABLE
postgres=# insert into employees(id, name) values(1, 'Jack');
INSERT 0 1
postgres=# insert into employees(id, name) values(2, 'Pulsar');
INSERT 0 1
postgres=# select * from employees;
id | name
----+--------
1 | Jack
2 | Pulsar
(2 rows)
The below are sample only, but you can extend this or devise your own execution method which makes your life easy. Let's see below how we can achieve this:
- Sample Test steps
- Config properties (useful for your env switching)
- Executor code (You can even more customize this for your project specific)
- Test Logs(collected from console logs or target logs)
{
"scenarioName": "Postgres DB SQL Executor - Simple and generic one, you can extend to ",
"steps": [
{
"name": "fetch_all",
"url": "com.xp.springboot.dbutils.PostGresSqlExecutor",
"operation": "executeSimpleSql",
"request": "select * from employees;",
"assertions": {
"rows.SIZE": 2,
"rows": [
{
"id": 1,
"name": "Jack"
},
{
"name": "Pulsar",
"id": 2
}
]
}
},
{
"name": "fetch_with_where",
"url": "com.xp.springboot.dbutils.PostGresSqlExecutor",
"operation": "executeSimpleSql",
"request": "select id, name from employees where name='${$.fetch_all.response.rows[1].name}';",
"assertions": {
"rows.SIZE": 1,
"rows": [
{
"id": 2,
"name": "${$.fetch_all.response.rows[1].name}"
}
]
}
}
]
}
This is where you DB host, user, password details goes along with REST/SOAP/Kafka application host.
# Web Server host and port
web.application.endpoint.host=http://localhost
web.application.endpoint.port=8080
web.application.endpoint.context=
## ---------------------------
## DB Host configs - Postgres
## ---------------------------
db_host_url=jdbc:postgresql://localhost:31435/postgres
db_username=replicaowner
db_password=password
Here the config properties are automatically injected, hence env switching does not affect this code.
public class PostGresSqlExecutor {
private static final Logger LOGGER = LoggerFactory.getLogger(PostGresSqlExecutor.class);
Map<String, List<Map<String, Object>>> dbRecordsMap = new HashMap<>();
public static final String RESULTS_KEY = "rows";
@Inject
@Named("db_host_url")
private String dbHostUrl;
@Inject
@Named("db_username")
private String dbUserName;
@Inject
@Named("db_password")
private String dbPassword;
public Map<String, List<Map<String, Object>>> executeSimpleSql(String simpleSql) {
LOGGER.info("DB - Executing SQL query: {}", simpleSql);
List<Map<String, Object>> recordsList = fetchDbRecords(simpleSql);
// -------------------------------------------------------
// Put all the fetched rows into nice JSON key and return.
// -- This make it better to assert SIZE etc in the steps.
// -- You can choose any key.
// -------------------------------------------------------
dbRecordsMap.put(RESULTS_KEY, recordsList);
return dbRecordsMap;
}
See the sample request/response after you have executed the test.
2018-11-30 15:50:07,869 [main] INFO com.xp.springboot.dbutils.PostGresSqlExecutor - DB - Executing SQL query: select * from employees;
2018-11-30 15:50:07,830 [main] INFO org.jsmart.zerocode.core.runner.ZeroCodeMultiStepsScenarioRunnerImpl -
----- BDD: Scenario:Postgres DB SQL Executor - Simple and generic one -------
--------- TEST-STEP-CORRELATION-ID: 09857cc4-b13b-48aa-aa52-10a21107a8db ---------
*requestTimeStamp:2018-11-30T15:50:07.857
step:fetch_all
url:com.xp.springboot.dbutils.PostGresSqlExecutor
method:executeSimpleSql
request:
"select * from employees;"
--------- TEST-STEP-CORRELATION-ID: 09857cc4-b13b-48aa-aa52-10a21107a8db ---------
Response:
{
"rows" : [ {
"name" : "Jack",
"id" : 1
}, {
"name" : "Pulsar",
"id" : 2
} ]
}
*responseTimeStamp:2018-11-30T15:50:07.958
*Response delay:101.0 milli-secs
---------> Assertion: <----------
{
"rows.SIZE" : 2,
"rows" : [ {
"id" : 1,
"name" : "Jack"
}, {
"name" : "Pulsar",
"id" : 2
} ]
}
-done-
2018-11-30 15:50:07,992 [main] INFO com.xp.springboot.dbutils.PostGresSqlExecutor - DB - Executing SQL query: select id, name from employees where name='Pulsar';
--------- TEST-STEP-CORRELATION-ID: 174d132d-07a9-46c0-a8a2-4fd3e38de960 ---------
*requestTimeStamp:2018-11-30T15:50:07.992
step:fetch_with_where
url:com.xp.springboot.dbutils.PostGresSqlExecutor
method:executeSimpleSql
request:
"select id, name from employees where name='Pulsar';"
--------- TEST-STEP-CORRELATION-ID: 174d132d-07a9-46c0-a8a2-4fd3e38de960 ---------
Response:
{
"rows" : [ {
"name" : "Pulsar",
"id" : 2
} ]
}
*responseTimeStamp:2018-11-30T15:50:08.002
*Response delay:10.0 milli-secs
---------> Assertion: <----------
{
"rows.SIZE" : 1,
"rows" : [ {
"id" : 2,
"name" : "Pulsar"
} ]
}
-done-
This is for PostGres
one, you need to add the similar driver dependencies for Oracle
or Sybase
or MySql
etc.
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>${version.postgresql}</version>
</dependency>
Visit the Zerocode Documentation Site for all things.
-
User's Guide
-
Matchers
-
Zerocode Value Tokens
-
YAML DSL
-
Http Testing
-
Kafka Testing
- Introduction
- Produce, consume proto message
- Produce raw message
- Consume raw message
- Produce JSON message
- Consume JSON message
- Produce and consume XML message
- Kafka - consume the latest message or n latest messages
- Produce avro message
- Consume avro message
- KSQL in action
- Produce multiple records
- Produce from file
- Produce to a partition
- Produce and consume records with headers
- Produce n assert partition ack
- Comsume and dump to file
- commitSync vs commitAsync
- Overriding config inside a test
- Chosing String or Int or Avro Serializer
- Chosing String or Int or Avro Deserializer
- Attaching timestamp during load
- Default timestamp provided by Kafka
- Consume and assert avro schema metadata
- Error handling - produce via avro schema
- Sorting Kafka records consumed
-
DB Testing
-
Kotlin Testing
-
Performance Testing - Load and Stress
- Performance Testing - via awesome JUnit runners
- Load Vs Stress generation on target application
- Run a single test or a scenario in parallel
- Run multiple test scenarios in parallel - Production load simulation
- Dynamically change the payload for every request
- Analytics - Useful report(s) or statistics
-
Parameterized Testing
-
Docker
-
More+
-
Extensions
-
JUnit5 Jupiter Test
-
Questions And Answers(FAQ)
- What is Zerocode testing?
- SSL http https connections supported?
- How to assert array size Greater-Than Lesser-Than etc?
- How to invoke POST api?
- How to assert custom headers of the response?
- How to pass custom security token into the request header?
- When to use JUnit Suite runner and when Zerocode Package runner?
- How to execute DB SQL and assert?
- How to handle Http response other than utf-8 e.g. utf-16 or utf-32 ?
- Random Number Generator Placeholders Usages and Limits
- Automation tests for Zerocode lib itself
- Picking a leaf value from the array matching JSON Path
- Array assertions made easy, incl. size and element finder
-
Read Our Blogs
- Top 16 Open Source API Testing Tools For REST & SOAP Services - joecolantonio (Lists popular tools - Globally)
- OAuth2 Test Automation - DZone 2min Read
- Zero defect APIs - Build Pipe Line - Medium 10 min Read
- Develop ZeroDefect API's with ZeroCode! - Extreme Portal ( A must read for all developers and test engineers) 10min Read
- Performance testing using JUnit and maven - Codeproject 10 min Read
- REST API or SOAP End Point Testing - Codeproject 10min Read
- DZone- MuleSoft API Testing With Zerocode Test Framework - DZone 5min Read
- Testing need not be harder or slower, it should be easier and faster - DZone 5 min Read
- Kotlin Integration Testing simplified via Zerocode - Extreme portal 10 min Read
- and More...