#!/usr/bin/env qore
# -*- mode: qore; indent-tabs-mode: nil -*-

%new-style
%enable-all-warnings
%require-types
%strict-args

# assert tests with no return value
%disable-warning return-value-ignored

%requires ../../../../qlib/QUnit.qm

%exec-class ParseDatasourceTest

public class ParseDatasourceTest inherits QUnit::Test {
    constructor() : Test("Parse_datasource test", "1.0") {
        addTestCase("Test 1", \test(), NOTHING);

        # Return for compatibility with test harness that checks return value.
        set_return_value(main());
    }

    test() {
        {
            hash<auto> dh = (
                "user"    : "user",
                "pass"    : "123pass@word",
                "db"      : "dbname",
                "charset" : "utf8",
                "host"    : "hostname",
            );
            string ds = "user/123pass@word@dbname(utf8)%hostname";

            assertEq(dh, parse_datasource(ds));
        }
        assertEq({
            "type": "sqlite3",
            "db": "/tmp/my-db.sqlite",
        }, parse_datasource("sqlite3:@/tmp/my-db.sqlite"));

        assertEq({
            "type": "sqlite3",
            "db": ":memory:",
        }, parse_datasource("sqlite3:@:memory:"));
        assertEq({
            "type": "test",
            "user": "a",
            "db": "b:x",
            "host": "c:x",
        }, parse_datasource("test:a@b:x%c:x"));
        assertEq({
            "type": "test",
            "user": "a",
            "db": "b",
            "host": "c:x",
        }, parse_datasource("test:a@b%c:x"));
        assertEq({
            "user": "a",
            "db": "b:x",
            "host": "c:x",
        }, parse_datasource("a@b:x%c:x"));
        assertEq({
            "user": "a",
            "db": "b",
            "host": "c:x",
        }, parse_datasource("a@b%c:x"));

        assertEq({
            "user": "a",
            "db": "b",
            "host": "c:x",
            "options": {
                "abc@xyz:1234": "123",
            },
        }, parse_datasource("a@b%c:x{abc@xyz:1234=123}"));

        assertEq({
            "type": "d",
            "user": "a",
            "pass": "b",
            "db": "c",
            "charset": "utf8",
            "host": "localhost",
            "port": 5432,
        }, parse_datasource("d:a/b@c(utf8)%localhost:5432"));

        assertThrows("DATASOURCE-PARSE-ERROR", "empty text", sub() { parse_datasource(""); });
        assertThrows("DATASOURCE-PARSE-ERROR", "missing closing parenthesis", sub() { parse_datasource("a@b("); });
        assertThrows("DATASOURCE-PARSE-ERROR", "missing hostname", sub() { parse_datasource("a@b%"); });
        assertThrows("DATASOURCE-PARSE-ERROR", "missing hostname", sub() { parse_datasource("a@b%{}"); });
        assertThrows("DATASOURCE-PARSE-ERROR", "invalid characters present", sub() { parse_datasource("a@b%c:12x2"); });
    }
}
