Skip to content

Commit

Permalink
Add basic tests
Browse files Browse the repository at this point in the history
  • Loading branch information
aashikam committed Feb 7, 2024
1 parent 7d398f7 commit 50b3123
Show file tree
Hide file tree
Showing 5 changed files with 285 additions and 0 deletions.
49 changes: 49 additions & 0 deletions ballerina/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,55 @@ clean {
delete 'build'
}

task startDatabaseServer() {
doLast {
if (!Os.isFamily(Os.FAMILY_WINDOWS)) {
def stdOut = new ByteArrayOutputStream()
exec {
commandLine 'sh', '-c', "docker ps --filter name=server-redshift-1"
standardOutput = stdOut
}
if (!stdOut.toString().contains("server-redshift-1")) {
println "Starting Redshift server."
exec {
commandLine 'sh', '-c', "docker-compose -f tests/server/docker-compose.yaml up -d"
standardOutput = stdOut
}
println stdOut.toString()
sleep(10 * 1000)
} else {
println "Redshift server is already started."
}
}
}
}

task stopDatabaseServer() {
doLast {
if (!Os.isFamily(Os.FAMILY_WINDOWS)) {
def stdOut = new ByteArrayOutputStream()
exec {
commandLine 'sh', '-c', "docker ps --filter name=server-redshift-1"
standardOutput = stdOut
}
if (stdOut.toString().contains("server-redshift-1")) {
println "Stopping RabbitMQ server."
exec {
commandLine 'sh', '-c', "docker-compose -f tests/server/docker-compose.yaml rm -svf"
standardOutput = stdOut
}
println stdOut.toString()
sleep(5 * 1000)
} else {
println "Redshift server is not started."
}
}
}
}

build.dependsOn copyToLib
build.dependsOn ":${packageName}-native:build"
test.dependsOn ":${packageName}-native:build"
test.dependsOn startDatabaseServer
build.finalizedBy stopDatabaseServer
publish.dependsOn build
54 changes: 54 additions & 0 deletions ballerina/tests/connection-tests.bal
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// Copyright (c) 2024 WSO2 LLC. (https://www.wso2.com) All Rights Reserved.
//
// WSO2 LLC. licenses this file to you under the Apache License,
// Version 2.0 (the "License"); you may not use this file except
// in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.

import ballerina/sql;
import ballerina/test;
import ballerinax/postgresql.driver as _;

@test:Config {
groups: ["connection"]
}
isolated function testConnectionInit() returns error? {
Client dbClient = check new (jdbcUrl, user, password);
error? closeResult = dbClient.close();
test:assertExactEquals(closeResult, (), "Initialising connection with url, user and password fields fails.");
}

@test:Config {
groups: ["connection"]
}
function testWithNamedArgs() returns error? {
Client dbClient = check new (password = password, user = user, url = jdbcUrl);
error? closeResult = dbClient.close();
test:assertExactEquals(closeResult, (), "Initialising connection with named args fails.");
}

@test:Config {
groups: ["connection"]
}
function testWithConnectionParams1() returns error? {
sql:ConnectionPool connectionPool = {
maxOpenConnections: 25,
maxConnectionLifeTime: 30,
minIdleConnections: 15
};
Options options = {
properties: {"ConnectionTimeout": "300"}
};
Client dbClient = check new (password = password, user = user, url = jdbcUrl, options = options, connectionPool = connectionPool);
error? closeResult = dbClient.close();
test:assertExactEquals(closeResult, (), "Initialising connection with connection params fails.");
}
19 changes: 19 additions & 0 deletions ballerina/tests/constants.bal
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// Copyright (c) 2024 WSO2 LLC. (https://www.wso2.com) All Rights Reserved.
//
// WSO2 LLC. licenses this file to you under the Apache License,
// Version 2.0 (the "License"); you may not use this file except
// in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.

final string & readonly jdbcUrl = "jdbc:postgresql://localhost:5432/postgres?ssl=false";
final string & readonly user = "postgres";
final string & readonly password = "password";
154 changes: 154 additions & 0 deletions ballerina/tests/execute-basic-test.bal
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
// Copyright (c) 2024 WSO2 LLC. (https://www.wso2.com) All Rights Reserved.
//
// WSO2 LLC. licenses this file to you under the Apache License,
// Version 2.0 (the "License"); you may not use this file except
// in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.

import ballerina/sql;
import ballerina/test;
import ballerinax/postgresql.driver as _;

@test:Config {
groups: ["execute"]
}
function testCreateTable() returns error? {
Client dbClient = check new (jdbcUrl, user, password);
sql:ExecutionResult result = check dbClient->execute(`
CREATE TABLE Student(student_id int, LastName varchar(255))
`);
check dbClient.close();
test:assertExactEquals(result.affectedRowCount, 0, "Affected row count is different.");
test:assertExactEquals(result.lastInsertId, (), "Last Insert Id is not nil.");
}

@test:Config {
groups: ["execute"],
dependsOn: [testCreateTable]
}
function testInsertTable() returns error? {
Client dbClient = check new (jdbcUrl, user, password);
sql:ExecutionResult result = check dbClient->execute(`Insert into Student (student_id) values (20)`);
check dbClient.close();

test:assertExactEquals(result.affectedRowCount, 1, "Affected row count is different.");
int|string? insertId = result.lastInsertId;
if insertId is int {
test:assertTrue(insertId > 1, "Last Insert Id is nil.");
} else {
test:assertFail("Insert Id should be an integer.");
}
}

@test:Config {
groups: ["execute"]
}
function testCreateTableWithDataTypes() returns error? {
Client dbClient = check new (jdbcUrl, user, password);
sql:ExecutionResult result = check dbClient->execute(`
CREATE TABLE DataTypesTest (
smallint_col SMALLINT,
int_col INTEGER NOT NULL,
bigint_col BIGINT,
decimal_col DECIMAL(10, 2),
real_col REAL,
double_col DOUBLE PRECISION,
boolean_col BOOLEAN,
char_col CHAR(10),
varchar_col VARCHAR(255),
date_col DATE,
timestamp_col TIMESTAMP,
timestamptz_col TIMESTAMPTZ,
time_col TIME,
timetz_col TIMETZ
)
`);
check dbClient.close();
test:assertExactEquals(result.affectedRowCount, 0, "Affected row count is different.");
test:assertExactEquals(result.lastInsertId, (), "Last Insert Id is not nil.");
}

@test:Config {
groups: ["execute"],
dependsOn: [testCreateTableWithDataTypes]
}
function testInsertDataWithDifferentTypes() returns error? {
Client dbClient = check new (jdbcUrl, user, password);
sql:ExecutionResult result = check dbClient->execute(`
INSERT INTO DataTypesTest VALUES
(1, 123, 1234567890, 123.45, 3.14, 6.28, true, 'TestChar', 'TestVarchar',
'2024-02-07', '2024-02-07 12:00:00', '2024-02-07 12:00:00+00:00',
'12:00:00', '12:00:00+00:00')
`);
check dbClient.close();
test:assertExactEquals(result.affectedRowCount, 1, "Affected row count is different.");
test:assertExactEquals(getInsertedNumericValue(), <decimal>123.45, "Numeric value mismatch.");
}

type DecimalColumn record {|
decimal decimal_col;
|};

function getInsertedNumericValue() returns decimal|error {
Client dbClient = check new (jdbcUrl, user, password);
stream<DecimalColumn, sql:Error?> decimalStream = dbClient->query(`SELECT decimal_col FROM DataTypesTest`);
check from DecimalColumn column in decimalStream
do {
return column.decimal_col;
};
return 0.0;
}

@test:Config {
groups: ["execute"],
dependsOn: [testCreateTableWithDataTypes]
}
function testInsertStringIntoIntegerColumn() returns error? {
Client dbClient = check new (jdbcUrl, user, password);
sql:ExecutionResult|sql:Error result = dbClient->execute(`
INSERT INTO DataTypesTest (int_col) VALUES ('InvalidString')
`);
check dbClient.close();
if result is sql:ExecutionResult {
test:assertFail("Expected a type mismatch error, but the query executed successfully.");
}
}

@test:Config {
groups: ["execute"],
dependsOn: [testCreateTableWithDataTypes]
}
function testInsertNullIntoNotNullColumn() returns error? {
Client dbClient = check new (jdbcUrl, user, password);
sql:ExecutionResult|sql:Error result = dbClient->execute(`
INSERT INTO DataTypesTest (int_col) VALUES (NULL)
`);
check dbClient.close();
if result is sql:ExecutionResult {
test:assertFail("Expected a NOT NULL constraint violation error, but the query executed successfully.");
}
}

@test:Config {
groups: ["execute"]
}
function testInvalidSqlQuery() returns error? {
Client dbClient = check new (jdbcUrl, user, password);
sql:ExecutionResult|sql:Error result = dbClient->execute(`
INVALID SQL QUERY
`);
check dbClient.close();
if result is sql:ExecutionResult {
test:assertFail("Expected an SQL syntax error, but the query executed successfully.");
}
}

9 changes: 9 additions & 0 deletions ballerina/tests/server/docker-compose.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
version: '3'

services:
redshift:
image: ghcr.io/hearthsim/docker-pgredshift:latest
environment:
POSTGRES_PASSWORD: password
ports:
- "5432:5432"

0 comments on commit 50b3123

Please sign in to comment.