From a3a9945eac73ae704a9fe39cc9aef763fce96743 Mon Sep 17 00:00:00 2001 From: Jakob Drees <32562853+WayneNani@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:10:25 +0100 Subject: [PATCH 1/3] Add parameterized tests: --%testcase and --%testcasesource Implements the design discussed in #1326: a --%test procedure with parameters runs once per test case. - --%testcase() runs a test once per annotation. A JSON array passes its values by position, a JSON object by parameter name (keys aren't case-sensitive). Values are literals; sysdate, constants etc. are provided by a --%testcasesource function. - --%testcasesource() runs a test once per test case returned by a function without required arguments: a json_array_t of JSON arrays and objects, or a sys_refcursor whose columns are matched to parameters by name. The function is called once, after beforeall; its test cases are kept until they have run. - Each test case is a separate test named [n]; a --%testcase case can be run alone by path. The description can refer to values with {1} or {}; without placeholders the values are appended. - JSON values are converted to the parameter types with json_value; date and time strings are ISO 8601, independent of NLS settings. Corner cases are reported with ORA-20220 and a message naming the value, column or parameter: - --%testcase arguments are checked when the suite is built (JSON array or object, number of values, keys, parameters without default); an invalid case gives a warning and is skipped. - JSON: unknown or duplicate keys, too many values, no value for a parameter without default, a value that isn't a JSON object or array for an object type or collection, unsupported parameter types and overloaded procedures. - Cursor: columns that are no parameter and aren't used in the description, parameters without default and without column, two columns for one parameter, object/collection/BOOLEAN columns that don't fit the parameter, overloaded procedures. Columns are passed by position only when no column is named like a parameter and their number equals the number of parameters. - A failing, missing or wrongly typed source function makes the test error; no test cases give a warning. Co-Authored-By: Claude Opus 5.5 --- docs/userguide/annotations.md | 298 +++- docs/userguide/running-unit-tests.md | 9 + source/core/types/ut_anydata_list.tps | 19 + source/core/types/ut_executable.tpb | 83 +- source/core/types/ut_executable.tps | 14 + source/core/types/ut_suite.tpb | 70 +- source/core/types/ut_suite_item.tpb | 5 + source/core/types/ut_suite_item.tps | 6 +- source/core/types/ut_test.tpb | 436 ++++++ source/core/types/ut_test.tps | 7 +- source/core/ut_metadata.pkb | 47 + source/core/ut_metadata.pks | 28 + source/core/ut_suite_builder.pkb | 208 ++- source/core/ut_suite_cache_macros.pkb | 3 +- source/core/ut_suite_cache_manager.pkb | 4 +- source/core/ut_suite_manager.pkb | 8 +- source/core/ut_test_case_json.pkb | 328 ++++ source/core/ut_test_case_json.pks | 48 + source/core/ut_test_case_values.pkb | 51 + source/core/ut_test_case_values.pks | 37 + source/core/ut_utils.pkb | 25 + source/core/ut_utils.pks | 21 + source/create_grants.sql | 1 + source/install.sql | 5 + source/reporters/ut_junit_reporter.tpb | 5 +- source/reporters/ut_teamcity_reporter.tpb | 4 +- source/reporters/ut_tfs_junit_reporter.tpb | 5 +- source/uninstall_objects.sql | 6 + test/install_ut3_user_tests.sql | 2 + test/ut3_tester/core/test_suite_builder.pkb | 227 +++ test/ut3_tester/core/test_suite_builder.pks | 38 + test/ut3_tester/core/test_ut_utils.pkb | 42 + test/ut3_tester/core/test_ut_utils.pks | 16 + test/ut3_user/api/test_ut_test_cases.pkb | 1494 +++++++++++++++++++ test/ut3_user/api/test_ut_test_cases.pks | 191 +++ 35 files changed, 3769 insertions(+), 22 deletions(-) create mode 100644 source/core/types/ut_anydata_list.tps create mode 100644 source/core/ut_test_case_json.pkb create mode 100644 source/core/ut_test_case_json.pks create mode 100644 source/core/ut_test_case_values.pkb create mode 100644 source/core/ut_test_case_values.pks create mode 100644 test/ut3_user/api/test_ut_test_cases.pkb create mode 100644 test/ut3_user/api/test_ut_test_cases.pks diff --git a/docs/userguide/annotations.md b/docs/userguide/annotations.md index 13ed97a23..75e24ab69 100644 --- a/docs/userguide/annotations.md +++ b/docs/userguide/annotations.md @@ -127,6 +127,8 @@ end; | `--%suitepath( )` | Package | Similar to java package. The annotation allows logical grouping of suites into hierarchies. | | `--%displayname( )` | Package/procedure | Human-readable and meaningful description of a context/suite/test. Overrides the `` provided with `suite`/`test`/`context` annotation. This annotation is redundant and might be removed in future releases. | | `--%test( )` | Procedure | Denotes that the annotated procedure is a unit test procedure. Optional test description can be provided (see `displayname`). | +| `--%testcase( )` | Procedure | Runs the annotated `%test` procedure once per `%testcase` annotation, passing the JSON values to the procedure. See [Testcase](#testcase). | +| `--%testcasesource( )` | Procedure | Runs the annotated `%test` procedure once per test case returned by the function (JSON array or cursor). See [Testcasesource](#testcasesource). | | `--%throws( [,...] )` | Procedure | Denotes that the annotated test procedure must throw one of the exceptions provided. Supported forms of exceptions are: numeric literals, numeric constant names, exception constant names, predefined Oracle exception names. | | `--%beforeall` | Procedure | Denotes that the annotated procedure should be executed once before all elements of the suite. | | `--%beforeall( [[.].][,...] )` | Package | Denotes that the mentioned procedure(s) should be executed once before all elements of the suite. | @@ -338,6 +340,299 @@ Finished in .008815 seconds 1 tests, 0 failed, 0 errored, 0 disabled, 1 warning(s) ``` +### Testcase + +The `--%testcase` annotation runs a `--%test` procedure once for each set of arguments, given as JSON. +Use it when the same check needs to be done for several inputs, for example boundary values. + +- Each `--%testcase` annotation becomes a separate test. It is reported, counted and run on its own, with its own `--%beforeeach`/`--%beforetest`/`--%aftertest`/`--%aftereach` calls and its own rollback. +- The arguments are a JSON array or a JSON object: an array passes its values by position, an object passes its values to the parameters named like its keys (not case-sensitive). + Parameters with default values can be omitted from an object, and at the end of an array. +- The values are converted to the data types of the parameters when the test case runs, see [JSON values](#json-values). + Dates and times are strings in ISO 8601 format, independent of the NLS settings of the session, see [Dates and times](#dates-and-times). +- JSON values are literals: they can't use `sysdate`, constants, function calls or object constructors. + For such values, use [`--%testcasesource`](#testcasesource) with a function that builds the JSON or returns a cursor. +- The test cases of a procedure are named `[1]`, `[2]`, ... in the order of the annotations. Running the procedure by path, for example `ut.run('test_get_discount.discount_by_customer_type')`, runs all of its test cases; `ut.run('test_get_discount.discount_by_customer_type[2]')` runs only the second one. +- `--%tags`, `--%throws`, `--%rollback`, `--%disabled` and `--%beforetest`/`--%aftertest` of the test procedure apply to every test case. + +The description of the `--%test` annotation can refer to the arguments of a test case: + +- `{1}`, `{2}`, ... is replaced with the first, second, ... value +- `{}` is replaced with the value passed to that parameter, by key or by position +- without any placeholder, the values are appended to the description in brackets + +Strings are shown without quotes, `null` as `null`. Values longer than 100 characters are shortened. + +```sql linenums="1" +create or replace function get_discount( + a_order_total number, + a_customer_type varchar2, + a_order_date date, + a_promo_start timestamp, + a_promo_end timestamp with time zone +) return number is + l_discount number; +begin + if a_customer_type = 'VIP' then + l_discount := 0.2; + elsif a_customer_type = 'REGULAR' then + l_discount := case when a_order_total >= 1000 then 0.1 else 0 end; + else + raise_application_error(-20001, 'Unknown customer type: ' || a_customer_type); + end if; + if a_order_date >= a_promo_start and a_order_date < a_promo_end then + l_discount := l_discount + 0.05; + end if; + return l_discount; +end; +/ +create or replace package test_get_discount as + + --%suite(Discount calculation) + + --%test(Discount for {a_customer_type} customer with order total {a_order_total} on {a_order_date} is {a_expected}) + --%testcase([500, "REGULAR", "2026-03-15T14:30:00", "2026-03-01T00:00:00.000000", "2026-03-31T23:59:59.999999+02:00", 0.05]) + --%testcase([1000, "REGULAR", "2026-04-01T09:00:00", "2026-03-01T00:00:00.000000", "2026-03-31T23:59:59.999999+02:00", 0.1]) + --%testcase({"a_order_total": 50, "a_customer_type": "VIP", "a_order_date": "2026-03-20T10:00:00", "a_promo_start": "2026-03-01T00:00:00.000000", "a_promo_end": "2026-03-31T23:59:59.999999-05:00", "a_expected": 0.25}) + --%testcase({"a_order_total": null, "a_customer_type": "REGULAR", "a_order_date": "2026-02-28T23:59:59", "a_promo_start": "2026-03-01T00:00:00.000000", "a_promo_end": "2026-03-31T23:59:59.999999+02:00", "a_expected": 0}) + procedure discount_by_customer_type( + a_order_total number, + a_customer_type varchar2, + a_order_date date, + a_promo_start timestamp, + a_promo_end timestamp with time zone, + a_expected number + ); + +end; +/ +create or replace package body test_get_discount as + + procedure discount_by_customer_type( + a_order_total number, + a_customer_type varchar2, + a_order_date date, + a_promo_start timestamp, + a_promo_end timestamp with time zone, + a_expected number + ) is + begin + ut.expect( + get_discount(a_order_total, a_customer_type, a_order_date, a_promo_start, a_promo_end) + ).to_equal( a_expected ); + end; + +end; +/ +``` +```sql linenums="1" +exec ut.run('test_get_discount'); +``` +``` +Discount calculation + Discount for REGULAR customer with order total 500 on 2026-03-15T14:30:00 is 0.05 [.011 sec] + Discount for REGULAR customer with order total 1000 on 2026-04-01T09:00:00 is 0.1 [.004 sec] + Discount for VIP customer with order total 50 on 2026-03-20T10:00:00 is 0.25 [.004 sec] + Discount for REGULAR customer with order total null on 2026-02-28T23:59:59 is 0 [.003 sec] + +Finished in .041927 seconds +4 tests, 0 failed, 0 errored, 0 disabled, 0 warning(s) +``` + +The whole annotation must fit in one line and end with the closing bracket; a comment after the annotation is not allowed. +Using `--%testcase` on a procedure without `--%test` gives a warning and the annotation is ignored. + +When the suite is built, the arguments of each test case are checked: they must be a valid JSON array or object, +and the number of values, the keys and the parameters without default value must fit the parameters of the test procedure. +A test case with invalid arguments gives a warning and is skipped; the numbers of the other test cases don't change. +Types are checked when the test case runs: a value that can't be converted to its parameter type makes only that test case error. + +### Testcasesource + +The `--%testcasesource` annotation runs a `--%test` procedure once for each test case returned by a function. +It suits many test cases and test cases computed with `sysdate`, constants or data from tables. + +The function takes no arguments (or only arguments with default values) and returns either + +- a `json_array_t`: each element is a test case, given as a JSON array or JSON object like the JSON of `--%testcase`, or +- a `sys_refcursor`: each row is a test case. Columns named like a parameter of the test procedure (not case-sensitive) are passed to that parameter; + other columns are not passed, but can be used in the description. If no column is named like a parameter, all columns are passed by position, + see [Cursor columns](#cursor-columns). + +The function is given by name: `discount_cases` for a function in the test package, `.` or `..` for a function elsewhere. + +```sql linenums="1" +create or replace package test_get_discount as + + --%suite(Discount calculation) + + --%test(Discount for {a_customer_type} customer with order total {a_order_total} on {a_order_date} is {a_expected}) + --%testcasesource(discount_cases) + procedure discount_by_customer_type( + a_order_total number, + a_customer_type varchar2, + a_order_date date, + a_promo_start timestamp, + a_promo_end timestamp with time zone, + a_expected number + ); + + function discount_cases return json_array_t; + +end; +/ +``` + +A function returning JSON (the procedure `discount_by_customer_type` is the same as above): + +```sql linenums="1" + function discount_cases return json_array_t is + begin + return json_array_t(q'[ + [ + [500, "REGULAR", "2026-03-15T14:30:00", "2026-03-01T00:00:00.000000", "2026-03-31T23:59:59.999999+02:00", 0.05], + [1000, "REGULAR", "2026-04-01T09:00:00", "2026-03-01T00:00:00.000000", "2026-03-31T23:59:59.999999+02:00", 0.1], + { + "a_order_total": 50, + "a_customer_type": "VIP", + "a_order_date": "2026-03-20T10:00:00", + "a_promo_start": "2026-03-01T00:00:00.000000", + "a_promo_end": "2026-03-31T23:59:59.999999-05:00", + "a_expected": 0.25 + }, + { + "a_order_total": null, + "a_customer_type": "REGULAR", + "a_order_date": "2026-02-28T23:59:59", + "a_promo_start": "2026-03-01T00:00:00.000000", + "a_promo_end": "2026-03-31T23:59:59.999999+02:00", + "a_expected": 0 + } + ] + ]'); + end; +``` + +A function returning a cursor (declared as `function discount_cases return sys_refcursor;`): + +```sql linenums="1" + function discount_cases return sys_refcursor is + l_cursor sys_refcursor; + begin + open l_cursor for + select 500 as a_order_total, + 'REGULAR' as a_customer_type, + to_date('2026-03-15 14:30:00', 'yyyy-mm-dd hh24:mi:ss') as a_order_date, + to_timestamp('2026-03-01 00:00:00.000000', 'yyyy-mm-dd hh24:mi:ss.ff') as a_promo_start, + to_timestamp_tz('2026-03-31 23:59:59.999999 +02:00', 'yyyy-mm-dd hh24:mi:ss.ff tzh:tzm') as a_promo_end, + 0.05 as a_expected + from dual + union all + select 1000, 'REGULAR', + to_date('2026-04-01 09:00:00', 'yyyy-mm-dd hh24:mi:ss'), + to_timestamp('2026-03-01 00:00:00.000000', 'yyyy-mm-dd hh24:mi:ss.ff'), + to_timestamp_tz('2026-03-31 23:59:59.999999 +02:00', 'yyyy-mm-dd hh24:mi:ss.ff tzh:tzm'), + 0.1 + from dual + union all + select 50, 'VIP', + to_date('2026-03-20 10:00:00', 'yyyy-mm-dd hh24:mi:ss'), + to_timestamp('2026-03-01 00:00:00.000000', 'yyyy-mm-dd hh24:mi:ss.ff'), + to_timestamp_tz('2026-03-31 23:59:59.999999 -05:00', 'yyyy-mm-dd hh24:mi:ss.ff tzh:tzm'), + 0.25 + from dual + union all + select null, 'REGULAR', + to_date('2026-02-28 23:59:59', 'yyyy-mm-dd hh24:mi:ss'), + to_timestamp('2026-03-01 00:00:00.000000', 'yyyy-mm-dd hh24:mi:ss.ff'), + to_timestamp_tz('2026-03-31 23:59:59.999999 +02:00', 'yyyy-mm-dd hh24:mi:ss.ff tzh:tzm'), + 0 + from dual; + return l_cursor; + end; +``` + +All variants give the same test cases and descriptions as the `--%testcase` example above. + +- The function is called when the suite runs, after its `--%beforeall` procedures, so it sees the data they create. It is called once, and the test cases it returns are kept in memory + until they have run, so changes to the data in `--%beforeeach`, `--%beforetest` or earlier test cases don't affect later test cases. +- A JSON array can be written as a literal, or built with SQL (`json_array`, `json_object`, `json_arrayagg`) or the PL/SQL JSON API (`json_array_t`, `json_object_t`), + which can use `sysdate`, constants and data from tables. `json_arrayagg` returns `null` when there are no rows, and `json_array_t` can't parse `null`, + so wrap it with `nvl`: `return json_array_t(nvl(l_json, '[]'));`. A function that returns `null` has no test cases. +- Each test case becomes a separate test, named `[1]`, `[2]`, ... in the order the function returns them. Each test case is rolled back as usual. +- The description can refer to the values of a test case with `{1}`, `{2}`, ... (position) and `{}` (JSON key, column name, + or for the values of a JSON array the name of the parameter they are passed to). + Without any placeholder, the values are appended to the description in brackets. Values of a cursor are shown like in JSON: + dates and times in ISO 8601 format and numbers with a leading zero, e.g. `0.05`. +- If the function fails, doesn't exist, returns another type than `json_array_t` or `sys_refcursor`, or returns an element that is neither a JSON array nor a JSON object, + the test is reported as errored. + If it returns no test cases (an empty array, `null` or no rows), the suite gets a warning. +- A disabled test doesn't call its function. +- `--%testcasesource` can't be combined with `--%testcase` on the same procedure. +- Running a single test case by path, for example `ut.run('test_get_discount.discount_by_customer_type[2]')`, is not supported, as the test cases are only known when the suite runs. +- Reporters that list all tests before the run, such as `ut_realtime_reporter`, list the test once, as its test cases are not known yet. + +#### Cursor columns + +The columns of a cursor are checked against the parameters of the test procedure before the first test case runs. +Each of the following makes the test error with `ORA-20220` and a message that names the column or parameter: + +- a column that is not named like a parameter and isn't used in the description (`{}` or `{}`), + so that a misspelled column name doesn't silently leave its parameter at the default value +- a parameter without default value that has no column +- two columns named like the same parameter, e.g. `a_amount` and `"a_amount"` +- no column named like a parameter, and the number of columns differs from the number of parameters +- a column whose type can't be passed to its parameter: object types and collections must be of the parameter type, + `BOOLEAN` columns only fit `BOOLEAN` parameters, and other values don't fit object type, collection, record or `BOOLEAN` parameters. + Other values are converted by PL/SQL; a value that can't be converted, for example `'abc'` for a `NUMBER`, makes only its test case error. +- an overloaded test procedure + +Cursor columns can have these data types: `VARCHAR2`, `CHAR`, `NVARCHAR2`, `NCHAR`, `NUMBER`, `BINARY_FLOAT`, `BINARY_DOUBLE`, `DATE`, `TIMESTAMP` (also with (local) time zone), +`INTERVAL`, `CLOB`, `NCLOB`, `BLOB`, `RAW`, `BOOLEAN` (Oracle 23 and later) and object types and collections that are not owned by `SYS`. +The values keep their type. Other types, such as `XMLTYPE`, make the test error with `ORA-20220`. + +#### JSON values + +JSON values of `--%testcase` and `--%testcasesource` are converted to the data type of the parameter they are passed to: + +| Parameter type | JSON value | +|---|---| +| `NUMBER`, `BINARY_FLOAT`, `BINARY_DOUBLE`, `PLS_INTEGER` | number, e.g. `0.05`, or a string with a number, e.g. `"0.05"` | +| `VARCHAR2`, `CHAR`, `NVARCHAR2`, `NCHAR`, `CLOB`, `NCLOB` | string, e.g. `"VIP"`; a number is converted to a string | +| `BOOLEAN` | `true` or `false` | +| `DATE`, `TIMESTAMP`, `TIMESTAMP WITH (LOCAL) TIME ZONE` | string in ISO 8601 format, see [Dates and times](#dates-and-times) | +| `INTERVAL DAY TO SECOND`, `INTERVAL YEAR TO MONTH` | ISO 8601 duration or Oracle interval string, e.g. `"P1DT2H"` or `"1 02:00:00"` | +| `RAW` | hexadecimal string, e.g. `"0AFF"` | +| object type | JSON object with all attributes as keys, e.g. `{"sku": "A", "qty": 1, "unit_price": 100}` | +| collection (nested table, varray) | JSON array, e.g. `[1, 2, 3]` | + +- `null` passes `NULL` for every type. +- A value that can't be converted, for example `"abc"` for a `NUMBER`, a value that is no JSON object for an object type or no JSON array for a collection, + or an object with a missing or unknown attribute, makes that test case error; the other test cases run. + So does a test case without value for a parameter that has no default value. +- Other parameter types, such as `BLOB`, `XMLTYPE`, records and PL/SQL collections, can't be passed from JSON; such test cases error with `ORA-20220`. +- JSON test cases can't be used with overloaded test procedures. + +The following was decided on purpose (see [discussion #1326](https://github.com/utPLSQL/utPLSQL/discussions/1326)): + +- **A JSON key that is no parameter of the test procedure is an error**, also when the key is meant only for the description. + A misspelled key would otherwise silently leave its parameter at the default value, and the test would check something else than it says. + Values for the description only can be returned by a cursor, whose extra columns are not passed to the procedure. +- **A `--%testcasesource` function returns `json_array_t`, not JSON text** (`clob`, `varchar2`). The type ensures that the function returns a JSON array: + invalid JSON or a JSON object raise an error in the function itself, where it is easy to find. + +#### Dates and times + +Date and time strings in the JSON of `--%testcase` and of a `--%testcasesource` function +are read in ISO 8601 format: `yyyy-mm-dd`, optionally followed by `Thh24:mi:ss`, fractional seconds after a `.` and a time zone such as `+02:00`, ` -05:00` or `Z`. +The NLS settings of the session don't matter. The values are then assigned to the parameter like in PL/SQL: + +- For `DATE` and `TIMESTAMP` parameters, a time zone in the string is dropped; the date and time are passed as written. +- For `TIMESTAMP WITH TIME ZONE` parameters, a string without time zone gets the time zone of the session. +- For `TIMESTAMP WITH LOCAL TIME ZONE` parameters, the value is converted to the time zone of the session. + +`json_object` and `json_object_t.put` write `DATE` and `TIMESTAMP` values in this format, so JSON built with SQL or the PL/SQL JSON API converts back without loss. + ### Disabled Marks annotated suite package or test procedure as disabled. You can provide the reason why the test is disabled that will be displayed in output. @@ -1080,6 +1375,7 @@ Finished in .015185 seconds ``` + ### Aftertest Indicates specific cleanup procedure(s) to be executed for a test. The procedure(s) can be located either: @@ -2149,7 +2445,7 @@ Following attributes are populated: | CONTEXT_PATH | suite context | the suitepath for the currently executed test suite context | | CONTEXT_START_TIME | suite context | the execution start timestamp for the currently executed test suite context | | TEST_DESCRIPTION | test* | the description of test for which the current executable is being invoked | -| TEST_NAME | test* | the name of test for which the current executable is being invoked | +| TEST_NAME | test* | the name of test for which the current executable is being invoked; for a test case it ends with the case number, e.g. `owner.package.test[2]` | | TEST_START_TIME | test* | the execution start timestamp of test that is currently being executed (the time when first `beforeeach`/`beforetest` was called for that test) | !!! note "Scopes" diff --git a/docs/userguide/running-unit-tests.md b/docs/userguide/running-unit-tests.md index a4797b735..f66745429 100644 --- a/docs/userguide/running-unit-tests.md +++ b/docs/userguide/running-unit-tests.md @@ -115,6 +115,15 @@ end; Executes single test procedure _hr.test_apply_bonus.bonus_cannot_be_negative_. +```sql linenums="1" +set serveroutput on +begin + ut.run('hr.test_apply_bonus.bonus_for_amount[2]'); +end; +``` +Executes only the second test case of the test procedure _hr.test_apply_bonus.bonus_for_amount_, see [Testcase](annotations.md#testcase). + + ```sql linenums="1" set serveroutput on begin diff --git a/source/core/types/ut_anydata_list.tps b/source/core/types/ut_anydata_list.tps new file mode 100644 index 000000000..2015ef862 --- /dev/null +++ b/source/core/types/ut_anydata_list.tps @@ -0,0 +1,19 @@ +create or replace noneditionable type ut_anydata_list as + /* + utPLSQL - Version 3 + Copyright 2016 - 2026 utPLSQL Project + + Licensed 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. + */ + table of sys.anydata +/ diff --git a/source/core/types/ut_executable.tpb b/source/core/types/ut_executable.tpb index 5d454989d..dc0b25116 100644 --- a/source/core/types/ut_executable.tpb +++ b/source/core/types/ut_executable.tpb @@ -55,7 +55,12 @@ create or replace noneditionable type body ut_executable is a_ignored_exception_names in ut_varchar2_rows := null, a_ignored_exception_numbers in ut_varchar2_rows :=null) return boolean is - l_statement varchar2(4000); + l_statement varchar2(32767); + l_call varchar2(32767); + l_values ut_anydata_list; + l_json clob; + l_call_error varchar2(32767); + l_parse_error varchar2(32767); l_status number; l_cursor_number number; l_completed_without_errors boolean := true; @@ -63,6 +68,39 @@ create or replace noneditionable type body ut_executable is l_start_transaction_id varchar2(250); l_end_transaction_id varchar2(250); + /* + Unpacks the argument values of a --%testcasesource test case, bound as :ut_values. + Object types and collections need a variable of their type; other values are read by the call itself. + */ + function get_test_case_call(a_values ut_anydata_list, a_call varchar2) return varchar2 is + l_declarations varchar2(32767); + l_unpacking varchar2(32767); + l_type anytype; + l_typecode pls_integer; + begin + for i in 1 .. a_values.count loop + -- the type code, as gettypename raises no_data_found for an NCLOB + l_typecode := a_values(i).gettype(l_type); + if l_typecode in (dbms_types.typecode_object, dbms_types.typecode_namedcollection, dbms_types.typecode_varray, dbms_types.typecode_table) then + l_declarations := l_declarations || + ' l_ut_value_' || i || ' "' || replace(a_values(i).gettypename(), '.', '"."') || '";' || chr(10); + l_unpacking := l_unpacking || + ' l_ut_rc := l_ut_values(' || i || ').' || + case when l_typecode = dbms_types.typecode_object then 'getobject' else 'getcollection' end || + '(l_ut_value_' || i || ');' || chr(10); + end if; + end loop; + return + 'declare' || chr(10) || + ' l_ut_values ' || ut_utils.ut_owner || '.ut_anydata_list := :ut_values;' || chr(10) || + ' l_ut_rc pls_integer;' || chr(10) || + l_declarations || + ' begin' || chr(10) || + l_unpacking || + ' ' || a_call || chr(10) || + ' end;'; + end; + function is_defined return boolean is l_result boolean := false; l_message_part varchar2(4000) := 'Call params for ' || self.executable_type || ' are not valid: '; @@ -86,7 +124,7 @@ create or replace noneditionable type body ut_executable is if not ut_metadata.package_valid(self.owner_name, self.object_name) then self.error_stack := l_message_part || 'package '||upper(self.owner_name||'.'||self.object_name)||' does not exist or is invalid.'; - elsif not ut_metadata.procedure_exists(self.owner_name, self.object_name, self.procedure_name) then + elsif not ut_metadata.procedure_exists(upper(self.owner_name), upper(self.object_name), upper(self.procedure_name)) then self.error_stack := l_message_part || 'procedure '||upper(self.owner_name || '.' || self.object_name || '.' ||self.procedure_name)||' does not exist.'; else l_result := false; @@ -119,6 +157,32 @@ create or replace noneditionable type body ut_executable is l_completed_without_errors := is_defined(); if l_completed_without_errors then + begin + if self.call_source is not null then + l_json := ut_test_case_values.get_json(a_item.path); + if l_json is null then + l_call := self.form_name( a_skip_current_user_schema => true ) || '(' || self.call_arguments || ');'; + -- without its values (e.g. package state was reset) the test case errors when it reads them, instead of breaking the run + l_values := coalesce(ut_test_case_values.get_values(a_item.path), ut_anydata_list()); + l_call := get_test_case_call(l_values, l_call); + end if; + elsif self.call_arguments is not null then + -- the arguments of a --%testcase are JSON + l_json := self.call_arguments; + else + l_call := self.form_name( a_skip_current_user_schema => true ) || ';'; + end if; + if l_json is not null then + l_call := ut_test_case_json.get_call( + self.owner_name, self.object_name, self.procedure_name, self.form_name( a_skip_current_user_schema => true ), l_json + ); + end if; + exception + when others then + -- JSON values that don't fit the parameters are an error of this test case, not of the run + l_call_error := dbms_utility.format_error_stack; + l_call := 'null;'; + end; l_statement := 'declare' || chr(10) || ' l_error_stack varchar2(32767);' || chr(10) || @@ -126,7 +190,7 @@ create or replace noneditionable type body ut_executable is ' l_ignored_exception_detected integer := 0;' || chr(10) || 'begin' || chr(10) || ' begin' || chr(10) || - ' ' || self.form_name( a_skip_current_user_schema => true ) || ';' || chr(10) || + ' ' || l_call || chr(10) || ' exception' || chr(10) || case when a_ignored_exception_names is not empty then ' when ' || ut_utils.table_to_clob( a_ignored_exception_names, ' or ' ) || ' then ' || chr(10) || @@ -161,6 +225,11 @@ create or replace noneditionable type body ut_executable is **/ begin dbms_sql.parse(l_cursor_number, statement => l_statement, language_flag => dbms_sql.native); + if l_call_error is null and l_values is not null then + dbms_sql.bind_variable(l_cursor_number, 'ut_values', l_values); + elsif l_call_error is null and l_json is not null then + dbms_sql.bind_variable(l_cursor_number, 'ut_json', l_json); + end if; dbms_sql.bind_variable(l_cursor_number, 'a_error_stack', to_char(null), 32767); dbms_sql.bind_variable(l_cursor_number, 'a_error_backtrace', to_char(null), 32767); dbms_sql.bind_variable(l_cursor_number, 'a_ignored_exception_detected', to_number(null)); @@ -171,10 +240,13 @@ create or replace noneditionable type body ut_executable is dbms_sql.close_cursor(l_cursor_number); exception when ut_utils.ex_invalid_package then + l_parse_error := dbms_utility.format_error_stack; l_failed_with_invalid_pck := is_invalid(); dbms_sql.close_cursor(l_cursor_number); - if not l_failed_with_invalid_pck then - raise; + if not l_failed_with_invalid_pck then + -- the call itself doesn't compile, e.g. arguments that don't fit the parameters; + -- that is an error of this executable, not of the whole run + self.error_stack := l_parse_error; end if; when others then dbms_sql.close_cursor(l_cursor_number); @@ -182,6 +254,7 @@ create or replace noneditionable type body ut_executable is end; save_dbms_output; + self.error_stack := coalesce(l_call_error, self.error_stack); l_completed_without_errors := (self.error_stack||self.error_backtrace) is null; if self.error_stack like '%ORA-04068%' or self.error_stack like '%ORA-04061%' then diff --git a/source/core/types/ut_executable.tps b/source/core/types/ut_executable.tps index 4e263402d..4f80f0beb 100644 --- a/source/core/types/ut_executable.tps +++ b/source/core/types/ut_executable.tps @@ -30,6 +30,20 @@ create or replace noneditionable type ut_executable under ut_event_item( * Used for ordering of executables, as Oracle doesn not guarantee ordering of items in a nested table. */ seq_no integer, + /** + * Arguments passed to the procedure: the JSON array or object of a --%testcase, e.g. ["VIP", 2000], + * or for a row of a --%testcasesource cursor the generated argument list that reads its values + */ + call_arguments varchar2(4000 char), + /** + * Function of a --%testcasesource annotation + */ + call_source varchar2(4000 char), + /** + * Number of the test case (element or row) the call_source function returned; null for the test that is not yet split + * into its test cases. The values of the test case are kept in ut_test_case_values. + */ + call_source_row integer, constructor function ut_executable( self in out nocopy ut_executable, a_owner varchar2, a_package varchar2, a_procedure_name varchar2, a_executable_type varchar2) return self as result, member function form_name(a_skip_current_user_schema boolean := false) return varchar2, member procedure do_execute( diff --git a/source/core/types/ut_suite.tpb b/source/core/types/ut_suite.tpb index 7012dee97..63ef50ce2 100644 --- a/source/core/types/ut_suite.tpb +++ b/source/core/types/ut_suite.tpb @@ -34,6 +34,66 @@ create or replace noneditionable type body ut_suite as l_suite_savepoint varchar2(30); l_no_errors boolean; + function has_test_case_sources return boolean is + begin + for i in 1 .. self.items.count loop + if self.items(i).has_test_case_source() then + return true; + end if; + end loop; + return false; + end; + + -- the --%testcasesource functions run after beforeall, so they see the data that beforeall created + procedure execute_with_test_case_sources is + l_items ut_suite_items := ut_suite_items(); + l_test ut_test; + l_cases ut_suite_items; + + procedure add_item(a_item ut_suite_item) is + begin + l_items.extend; + l_items(l_items.last) := a_item; + end; + begin + for i in 1 .. self.items.count loop + if self.items(i).has_test_case_source() and not self.items(i).get_disabled_flag() then + l_test := treat(self.items(i) as ut_test); + l_cases := null; + begin + l_cases := l_test.get_source_test_cases(); + exception + when others then + l_test.mark_as_errored('The --%testcasesource function failed.' || chr(10) || dbms_utility.format_error_stack); + add_item(l_test); + end; + if l_cases is not null then + if l_cases.count = 0 then + self.put_warning('The --%testcasesource function returned no test cases.', l_test.name, l_test.line_no); + end if; + for j in 1 .. l_cases.count loop + begin + l_cases(j).do_execute(); + exception + when others then + -- don't keep the values of the test cases that won't run + for k in j .. l_cases.count loop + ut_test_case_values.remove_values(l_cases(k).path); + end loop; + raise; + end; + ut_test_case_values.remove_values(l_cases(j).path); + add_item(l_cases(j)); + end loop; + end if; + else + self.items(i).do_execute(); + add_item(self.items(i)); + end if; + end loop; + self.items := l_items; + end; + procedure propagate_error(a_error_stack_trace varchar2) is begin for i in 1..self.items.count loop @@ -62,9 +122,13 @@ create or replace noneditionable type body ut_suite as end loop; if l_no_errors then - for i in 1 .. self.items.count loop - self.items(i).do_execute(); - end loop; + if has_test_case_sources() then + execute_with_test_case_sources(); + else + for i in 1 .. self.items.count loop + self.items(i).do_execute(); + end loop; + end if; end if; for i in 1 .. after_all_list.count loop diff --git a/source/core/types/ut_suite_item.tpb b/source/core/types/ut_suite_item.tpb index 01b9b0ee0..62806d158 100644 --- a/source/core/types/ut_suite_item.tpb +++ b/source/core/types/ut_suite_item.tpb @@ -121,5 +121,10 @@ create or replace noneditionable type body ut_suite_item as end if; end; + member function has_test_case_source(self in ut_suite_item) return boolean is + begin + return false; + end; + end; / diff --git a/source/core/types/ut_suite_item.tps b/source/core/types/ut_suite_item.tps index 556ff7f0b..c878ae45e 100644 --- a/source/core/types/ut_suite_item.tps +++ b/source/core/types/ut_suite_item.tps @@ -89,7 +89,11 @@ create or replace noneditionable type ut_suite_item force under ut_event_item ( not instantiable member function get_error_stack_traces return ut_varchar2_list, not instantiable member function get_serveroutputs return clob, member procedure put_warning(self in out nocopy ut_suite_item, a_message varchar2), - member procedure put_warning(self in out nocopy ut_suite_item, a_message varchar2, a_procedure_name varchar2, a_line_no integer) + member procedure put_warning(self in out nocopy ut_suite_item, a_message varchar2, a_procedure_name varchar2, a_line_no integer), + /** + * True for a test with a --%testcasesource query that is not yet split into its test cases. + */ + member function has_test_case_source(self in ut_suite_item) return boolean ) not final not instantiable / diff --git a/source/core/types/ut_test.tpb b/source/core/types/ut_test.tpb index c3577274c..8dfb4c00e 100644 --- a/source/core/types/ut_test.tpb +++ b/source/core/types/ut_test.tpb @@ -174,5 +174,441 @@ create or replace noneditionable type body ut_test as end loop; return l_results; end; + + overriding member function has_test_case_source(self in ut_test) return boolean is + begin + return self.item.call_source is not null and self.item.call_source_row is null; + end; + + member function get_source_test_cases(self in ut_test) return ut_suite_items is + l_parts ut_varchar2_list := ut_utils.string_to_table(upper(self.item.call_source), '.'); + l_owner varchar2(128 char); + l_package varchar2(128 char); + l_function varchar2(128 char); + l_function_call varchar2(1000 char); + l_return_type ut_metadata.t_parameter; + l_result ut_suite_items := ut_suite_items(); + + procedure raise_invalid(a_message varchar2) is + begin + raise_application_error( + ut_utils.gc_invalid_test_case_source, 'The --%testcasesource function ' || self.item.call_source || ' ' || a_message || '.' + ); + end; + + function add_test_case(a_row_no integer, a_description varchar2, a_call_arguments varchar2 := null) return varchar2 is + l_test ut_test := self; + begin + l_test.name := self.name || '[' || a_row_no || ']'; + l_test.path := self.path || '[' || a_row_no || ']'; + l_test.description := a_description; + l_test.item.call_source_row := a_row_no; + l_test.item.call_arguments := a_call_arguments; + l_result.extend; + l_result(l_result.last) := l_test; + return l_test.path; + end; + + -- each element of the array is a test case; its JSON text is converted to the parameter types when the test case runs + procedure add_json_test_cases is + l_json clob; + l_element json_element_t; + l_array json_array_t; + l_parameters ut_metadata.tt_parameters := + ut_metadata.get_package_parameters(upper(self.item.owner_name), upper(self.item.object_name), upper(self.item.procedure_name)); + l_names ut_varchar2_list := ut_varchar2_list(); + begin + for i in 1 .. l_parameters.count loop + if l_parameters(i).overload = l_parameters(1).overload and l_parameters(i).parameter_name is not null then + l_names.extend; + l_names(l_names.last) := l_parameters(i).parameter_name; + end if; + end loop; + execute immediate + 'declare l_ut_cases json_array_t := ' || l_function_call || ';' || + ' begin if l_ut_cases is not null then :ut_json := l_ut_cases.to_clob(); else :ut_json := null; end if; end;' + using out l_json; + -- a function that returns null has no test cases + if l_json is null then + return; + end if; + l_array := json_array_t.parse(l_json); + for i in 0 .. l_array.get_size - 1 loop + l_element := l_array.get(i); + if not (l_element.is_array or l_element.is_object) then + raise_invalid('returned element ' || (i + 1) || ', which is neither a JSON array nor a JSON object'); + end if; + l_json := l_element.to_clob; + ut_test_case_values.set_json( + add_test_case(i + 1, ut_test_case_json.get_test_case_description(self.description, l_json, l_names)), l_json + ); + end loop; + end; + + -- the rows of the cursor are fetched once; each test case gets the values of its row as ANYDATA + procedure add_cursor_test_cases is + type tt_positions is table of pls_integer index by pls_integer; + l_parameters ut_metadata.tt_parameters := + ut_metadata.get_package_parameters(upper(self.item.owner_name), upper(self.item.object_name), upper(self.item.procedure_name)); + l_params ut_metadata.tt_parameters := ut_metadata.tt_parameters(); + l_cursor integer; + l_columns dbms_sql.desc_tab3; + l_count integer; + l_named boolean; + l_param_of tt_positions; -- column -> the parameter it is passed to, 0 for none + l_column_of tt_positions; -- parameter -> the column passed to it + l_index pls_integer; + l_arguments varchar2(4000 char); + l_argument varchar2(4000 char); + l_declarations varchar2(32767); + l_defines varchar2(32767); + l_fetches varchar2(32767); + l_values_code varchar2(32767); + l_display_code varchar2(32767); + l_values ut_anydata_list; + l_display ut_varchar2_list; + l_row_values ut_anydata_list; + l_row_display ut_varchar2_list; + l_names ut_varchar2_list := ut_varchar2_list(); + + -- columns are matched to parameters like JSON keys, not case-sensitive + function find_parameter(a_column_name varchar2) return pls_integer is + l_position pls_integer := l_params.first; + begin + while l_position is not null loop + if upper(l_params(l_position).parameter_name) = upper(a_column_name) then + return l_position; + end if; + l_position := l_params.next(l_position); + end loop; + return 0; + end; + + function is_in_description(a_column_name varchar2, a_position integer) return boolean is + begin + return nvl( + instr(self.description, '{' || a_column_name || '}') > 0 + or instr(self.description, '{' || lower(a_column_name) || '}') > 0 + or instr(self.description, '{' || a_position || '}') > 0, + false + ); + end; + + -- PL/SQL converts scalar values implicitly; object types, collections and BOOLEAN must match the parameter + function fits(a_column dbms_sql.desc_rec3, a_parameter ut_metadata.t_parameter) return boolean is + begin + return nvl( + case + when a_column.col_type = 109 then + a_parameter.type_owner = a_column.col_schema_name and a_parameter.type_name = a_column.col_type_name + and a_parameter.type_subname is null + when a_column.col_type = 252 then + a_parameter.data_type in ('BOOLEAN', 'PL/SQL BOOLEAN') + else + a_parameter.type_name is null and a_parameter.data_type not in ('BOOLEAN', 'PL/SQL BOOLEAN') + end, + false + ); + end; + + function parameter_type(a_parameter ut_metadata.t_parameter) return varchar2 is + begin + return nvl( + -- no nvl2: before Oracle 21 it exists only in SQL, not in PL/SQL + a_parameter.type_owner || case when a_parameter.type_owner is not null then '.' end || a_parameter.type_name + || case when a_parameter.type_subname is not null then '.' || a_parameter.type_subname end, + a_parameter.data_type + ); + end; + + function is_collection(a_column dbms_sql.desc_rec3) return boolean is + l_typecode all_types.typecode%type; + begin + select /*+ no_parallel */ typecode into l_typecode + from all_types + where owner = a_column.col_schema_name and type_name = a_column.col_type_name; + return l_typecode = 'COLLECTION'; + end; + + function declaration(a_column dbms_sql.desc_rec3) return varchar2 is + l_national boolean := a_column.col_charsetform = 2; + begin + return + case a_column.col_type + when 1 then case when l_national then 'nvarchar2(32767)' else 'varchar2(32767)' end + when 96 then case when l_national then 'nvarchar2(32767)' else 'varchar2(32767)' end + when 2 then 'number' + when 100 then 'binary_float' + when 101 then 'binary_double' + when 12 then 'date' + when 180 then 'timestamp(9)' + when 181 then 'timestamp(9) with time zone' + when 231 then 'timestamp(9) with local time zone' + when 182 then 'interval year(9) to month' + when 183 then 'interval day(9) to second(9)' + when 112 then case when l_national then 'nclob' else 'clob' end + when 113 then 'blob' + when 23 then 'raw(32767)' + when 109 then '"' || a_column.col_schema_name || '"."' || a_column.col_type_name || '"' + when 252 then 'boolean' + end; + end; + + -- the value as ANYDATA; BOOLEAN has no ANYDATA representation, so it travels as 1 or 0 + function value_expression(a_column dbms_sql.desc_rec3, a_variable varchar2) return varchar2 is + l_national boolean := a_column.col_charsetform = 2; + begin + return 'sys.anydata.' || + case a_column.col_type + when 1 then case when l_national then 'convertnvarchar2' else 'convertvarchar2' end + when 96 then case when l_national then 'convertnvarchar2' else 'convertvarchar2' end + when 2 then 'convertnumber' + when 100 then 'convertbfloat' + when 101 then 'convertbdouble' + when 12 then 'convertdate' + when 180 then 'converttimestamp' + when 181 then 'converttimestamptz' + when 231 then 'converttimestampltz' + when 182 then 'convertintervalym' + when 183 then 'convertintervalds' + when 112 then case when l_national then 'convertnclob' else 'convertclob' end + when 113 then 'convertblob' + when 23 then 'convertraw' + when 109 then case when is_collection(a_column) then 'convertcollection' else 'convertobject' end + when 252 then 'convertnumber' + end || + case when a_column.col_type = 252 + then '(case when ' || a_variable || ' then 1 when not ' || a_variable || ' then 0 end)' + else '(' || a_variable || ')' + end; + end; + + -- the argument passed to the test procedure; ut_executable declares l_ut_value_ for object types and collections + function argument_expression(a_column dbms_sql.desc_rec3, a_position integer) return varchar2 is + l_value varchar2(200 char) := 'l_ut_values(' || a_position || ')'; + l_national boolean := a_column.col_charsetform = 2; + begin + return + case a_column.col_type + when 1 then l_value || case when l_national then '.accessnvarchar2()' else '.accessvarchar2()' end + when 96 then l_value || case when l_national then '.accessnvarchar2()' else '.accessvarchar2()' end + when 2 then l_value || '.accessnumber()' + when 100 then l_value || '.accessbfloat()' + when 101 then l_value || '.accessbdouble()' + when 12 then l_value || '.accessdate()' + when 180 then l_value || '.accesstimestamp()' + when 181 then l_value || '.accesstimestamptz()' + when 231 then l_value || '.accesstimestampltz()' + when 182 then l_value || '.accessintervalym()' + when 183 then l_value || '.accessintervalds()' + when 112 then l_value || case when l_national then '.accessnclob()' else '.accessclob()' end + when 113 then l_value || '.accessblob()' + when 23 then l_value || '.accessraw()' + when 109 then 'l_ut_value_' || a_position + when 252 then 'case ' || l_value || '.accessnumber() when 1 then true when 0 then false end' + end; + end; + + -- values are shown like in a JSON or PL/SQL test case: dates and times in ISO format, numbers with a leading zero + function display_expression(a_column dbms_sql.desc_rec3, a_variable varchar2) return varchar2 is + begin + return + case + when a_column.col_type = 12 then 'to_char(' || a_variable || ', ''yyyy-mm-dd"T"hh24:mi:ss'')' + when a_column.col_type = 180 then 'to_char(' || a_variable || ', ''yyyy-mm-dd"T"hh24:mi:ss.ff6'')' + when a_column.col_type = 181 then 'to_char(' || a_variable || ', ''yyyy-mm-dd"T"hh24:mi:ss.ff6tzh:tzm'')' + when a_column.col_type = 231 then + 'to_char(cast(' || a_variable || ' as timestamp with time zone), ''yyyy-mm-dd"T"hh24:mi:ss.ff6tzh:tzm'')' + when a_column.col_type in (2, 100, 101) then + 'regexp_replace(to_char(' || a_variable || ', ''TM9'', ''nls_numeric_characters=''''.,''''''), ''^(-?)\.'', ''\10.'')' + when a_column.col_type in (1, 96, 182, 183) then 'to_char(' || a_variable || ')' + when a_column.col_type = 112 then 'dbms_lob.substr(' || a_variable || ', 100)' + when a_column.col_type = 23 then 'rawtohex(' || a_variable || ')' + when a_column.col_type = 252 then 'case when ' || a_variable || ' then ''true'' when not ' || a_variable || ' then ''false'' end' + else '''<' || nvl(a_column.col_type_name, 'value') || '>''' + end; + end; + begin + l_index := l_parameters.first; + while l_index is not null loop + if l_parameters(l_index).overload != l_parameters(l_parameters.first).overload then + raise_invalid('can''t be used with the overloaded procedure ' || upper(self.item.procedure_name)); + end if; + if l_parameters(l_index).parameter_name is not null then + l_params.extend; + l_params(l_params.last) := l_parameters(l_index); + end if; + l_index := l_parameters.next(l_index); + end loop; + execute immediate + 'declare l_ut_rc sys_refcursor; begin l_ut_rc := ' || l_function_call || '; :ut_cursor := dbms_sql.to_cursor_number(l_ut_rc); end;' + using out l_cursor; + begin + dbms_sql.describe_columns3(l_cursor, l_count, l_columns); + for i in 1 .. l_count loop + if argument_expression(l_columns(i), i) is null + or l_columns(i).col_type = 109 and l_columns(i).col_schema_name = 'SYS' then + raise_invalid( + 'returned column ' || l_columns(i).col_name || ', which has a data type that can''t be passed to the test: ' + || nvl(l_columns(i).col_type_name, to_char(l_columns(i).col_type)) + ); + end if; + l_param_of(i) := find_parameter(l_columns(i).col_name); + if l_param_of(i) > 0 then + if l_column_of.exists(l_param_of(i)) then + raise_invalid( + 'returned columns ' || l_columns(l_column_of(l_param_of(i))).col_name || ' and ' || l_columns(i).col_name + || ' for the same parameter ' || l_params(l_param_of(i)).parameter_name + ); + end if; + l_column_of(l_param_of(i)) := i; + end if; + end loop; + -- columns named like parameters are passed by name; when none is, all columns are passed by position + l_named := l_column_of.count > 0; + if not l_named then + if l_count != l_params.count then + raise_invalid( + 'returned ' || l_count || ' column(s) and none is named like a parameter, but the test procedure has ' + || l_params.count || ' parameter(s); name the columns like the parameters or return one column per parameter' + ); + end if; + for i in 1 .. l_count loop + l_param_of(i) := i; + l_column_of(i) := i; + end loop; + end if; + -- a column that is neither passed nor shown is an error, so that a misspelled column name + -- doesn't silently leave its parameter at the default, like a misspelled JSON key + for i in 1 .. l_count loop + if l_param_of(i) = 0 and not is_in_description(l_columns(i).col_name, i) then + raise_invalid( + 'returned column ' || l_columns(i).col_name || ', which is no parameter of the test procedure and isn''t used in the description' + ); + elsif l_param_of(i) > 0 and not fits(l_columns(i), l_params(l_param_of(i))) then + raise_invalid( + 'returned column ' || l_columns(i).col_name || ' of type ' || upper(regexp_replace(declaration(l_columns(i)), '\([0-9]+\)')) + || ', which can''t be passed to parameter ' || l_params(l_param_of(i)).parameter_name + || ' of type ' || parameter_type(l_params(l_param_of(i))) + ); + end if; + end loop; + l_index := l_params.first; + while l_index is not null loop + if l_params(l_index).defaulted = 'N' and not l_column_of.exists(l_index) then + raise_invalid('returned no column for parameter ' || l_params(l_index).parameter_name || ', which has no default value'); + end if; + l_index := l_params.next(l_index); + end loop; + for i in 1 .. l_count loop + if l_param_of(i) > 0 then + l_argument := case when l_arguments is not null then ', ' end + || case when l_named then '"' || l_params(l_param_of(i)).parameter_name || '" => ' end + || argument_expression(l_columns(i), i); + if nvl(lengthc(l_arguments), 0) + lengthc(l_argument) > ut_utils.gc_max_storage_varchar2_len then + raise_invalid('returned more columns than can be passed to the test procedure'); + end if; + l_arguments := l_arguments || l_argument; + end if; + l_declarations := l_declarations || ' l_ut_v' || i || ' ' || declaration(l_columns(i)) || ';' || chr(10); + l_defines := l_defines || ' dbms_sql.' || + case + when l_columns(i).col_type = 23 then 'define_column_raw(l_ut_c, ' || i || ', l_ut_v' || i || ', 32767);' + when l_columns(i).col_type in (1, 96) then 'define_column(l_ut_c, ' || i || ', l_ut_v' || i || ', 32767);' + else 'define_column(l_ut_c, ' || i || ', l_ut_v' || i || ');' + end || chr(10); + l_fetches := l_fetches || ' dbms_sql.column_value' || case when l_columns(i).col_type = 23 then '_raw' end + || '(l_ut_c, ' || i || ', l_ut_v' || i || ');' || chr(10); + l_values_code := l_values_code || + ' l_ut_values(l_ut_values.count - ' || (l_count - i) || ') := ' || value_expression(l_columns(i), 'l_ut_v' || i) || ';' || chr(10); + l_display_code := l_display_code || + ' l_ut_display(l_ut_display.count - ' || (l_count - i) || ') := substr(' || display_expression(l_columns(i), 'l_ut_v' || i) + || ', 1, ' || ut_utils.gc_max_storage_varchar2_len || ');' || chr(10); + l_names.extend; + l_names(i) := l_columns(i).col_name; + end loop; + + execute immediate + 'declare' || chr(10) || + ' l_ut_c integer := :ut_cursor;' || chr(10) || + ' l_ut_values ' || ut_utils.ut_owner || '.ut_anydata_list := ' || ut_utils.ut_owner || '.ut_anydata_list();' || chr(10) || + ' l_ut_display ' || ut_utils.ut_owner || '.ut_varchar2_list := ' || ut_utils.ut_owner || '.ut_varchar2_list();' || chr(10) || + l_declarations || + 'begin' || chr(10) || + l_defines || + ' while dbms_sql.fetch_rows(l_ut_c) > 0 loop' || chr(10) || + l_fetches || + ' l_ut_values.extend(' || l_count || ');' || chr(10) || + ' l_ut_display.extend(' || l_count || ');' || chr(10) || + l_values_code || + l_display_code || + ' end loop;' || chr(10) || + ' dbms_sql.close_cursor(l_ut_c);' || chr(10) || + ' :ut_values := l_ut_values;' || chr(10) || + ' :ut_display := l_ut_display;' || chr(10) || + 'end;' + using in l_cursor, out l_values, out l_display; + exception + when others then + if dbms_sql.is_open(l_cursor) then + dbms_sql.close_cursor(l_cursor); + end if; + raise; + end; + + for l_row_no in 1 .. l_values.count / l_count loop + l_row_values := ut_anydata_list(); + l_row_display := ut_varchar2_list(); + for i in 1 .. l_count loop + l_row_values.extend; + l_row_values(i) := l_values((l_row_no - 1) * l_count + i); + l_row_display.extend; + l_row_display(i) := nvl(l_display((l_row_no - 1) * l_count + i), 'null'); + end loop; + ut_test_case_values.set_values( + add_test_case( + l_row_no, + ut_utils.get_test_case_description(self.description, l_names, l_row_display), + l_arguments + ), + l_row_values + ); + end loop; + end; + begin + case l_parts.count + when 1 then + l_owner := upper(self.item.owner_name); + l_package := upper(self.item.object_name); + l_function := l_parts(1); + when 2 then + l_owner := upper(self.item.owner_name); + l_package := l_parts(1); + l_function := l_parts(2); + else + l_owner := l_parts(1); + l_package := l_parts(2); + l_function := l_parts(3); + end case; + l_function_call := + dbms_assert.enquote_name(l_owner, false) || '.' || dbms_assert.enquote_name(l_package, false) || '.' + || dbms_assert.enquote_name(l_function, false) || '()'; + l_return_type := ut_metadata.get_function_return_type(l_owner, l_package, l_function); + case + when l_return_type.data_type = 'REF CURSOR' then + add_cursor_test_cases(); + -- json_array_t rather than text, so that what the function returns is a JSON array (decided in #1326) + when l_return_type.data_type = 'OBJECT' and l_return_type.type_name = 'JSON_ARRAY_T' then + add_json_test_cases(); + when l_return_type.data_type is null then + raise_invalid('doesn''t exist or can''t be called without arguments'); + else + raise_invalid( + 'must return json_array_t or sys_refcursor, not ' + || nvl(l_return_type.type_name, l_return_type.data_type) + ); + end case; + return l_result; + end; end; / diff --git a/source/core/types/ut_test.tps b/source/core/types/ut_test.tps index 7590abc35..594fc386e 100644 --- a/source/core/types/ut_test.tps +++ b/source/core/types/ut_test.tps @@ -65,6 +65,11 @@ create or replace noneditionable type ut_test force under ut_suite_item ( overriding member procedure mark_as_errored(self in out nocopy ut_test, a_error_stack_trace varchar2), overriding member function get_error_stack_traces(self ut_test) return ut_varchar2_list, overriding member function get_serveroutputs return clob, - member function get_failed_expectation_lines return ut_varchar2_rows + member function get_failed_expectation_lines return ut_varchar2_rows, + overriding member function has_test_case_source(self in ut_test) return boolean, + /** + * Calls the --%testcasesource function and returns one test for each element of its JSON array or row of its cursor. + */ + member function get_source_test_cases(self in ut_test) return ut_suite_items ) / diff --git a/source/core/ut_metadata.pkb b/source/core/ut_metadata.pkb index 7c89dc5ef..a67a9ab5e 100644 --- a/source/core/ut_metadata.pkb +++ b/source/core/ut_metadata.pkb @@ -69,6 +69,53 @@ create or replace noneditionable package body ut_metadata as return false; end; + function get_package_parameters( + a_owner_name varchar2, a_package_name varchar2, a_procedure_name varchar2 := null + ) return tt_parameters is + l_result tt_parameters; + l_procedures varchar2(200 char) := get_dba_view('dba_procedures'); + l_arguments varchar2(200 char) := get_dba_view('dba_arguments'); + begin + -- the outer join keeps procedures without parameters, which have no entries in dba_arguments + execute immediate + 'select /*+ no_parallel */ p.procedure_name, nvl(p.overload, ''0''), a.argument_name, a.defaulted,' || + ' a.data_type, a.type_owner, a.type_name, a.type_subname' || + ' from ' || l_procedures || ' p' || + ' left join ' || l_arguments || ' a' || + ' on a.owner = p.owner and a.package_name = p.object_name and a.object_name = p.procedure_name' || + ' and nvl(a.overload, ''0'') = nvl(p.overload, ''0'') and a.data_level = 0 and a.argument_name is not null' || + ' where p.owner = :a_owner_name and p.object_name = :a_package_name and p.procedure_name is not null' || + ' and (:a_procedure_name is null or p.procedure_name = :a_procedure_name)' || + ' order by p.procedure_name, p.overload, a.position' + bulk collect into l_result using a_owner_name, a_package_name, a_procedure_name, a_procedure_name; + return l_result; + end; + + function get_function_return_type( + a_owner_name varchar2, a_package_name varchar2, a_function_name varchar2 + ) return t_parameter is + l_result t_parameter; + l_view_name varchar2(200 char) := get_dba_view('dba_arguments'); + begin + execute immediate + 'select /*+ no_parallel */ r.object_name, nvl(r.overload, ''0''), null, null, r.data_type, r.type_owner, r.type_name, r.type_subname' || + ' from ' || l_view_name || ' r' || + ' where r.owner = :a_owner_name and r.package_name = :a_package_name and r.object_name = :a_function_name' || + ' and r.position = 0 and r.data_level = 0' || + ' and not exists (' || + ' select 1 from ' || l_view_name || ' a' || + ' where a.owner = r.owner and a.package_name = r.package_name and a.object_name = r.object_name' || + ' and nvl(a.overload, ''0'') = nvl(r.overload, ''0'') and a.position > 0 and a.data_level = 0' || + ' and a.defaulted = ''N''' || + ' )' || + ' order by r.overload fetch first 1 row only' + into l_result using a_owner_name, a_package_name, a_function_name; + return l_result; + exception + when no_data_found then + return l_result; + end; + function get_source_definition_line(a_owner varchar2, a_object_name varchar2, a_line_no integer) return varchar2 is l_view_name varchar2(128) := get_source_view_name(); l_line all_source.text%type; diff --git a/source/core/ut_metadata.pks b/source/core/ut_metadata.pks index f320e7bf8..5b4f8378d 100644 --- a/source/core/ut_metadata.pks +++ b/source/core/ut_metadata.pks @@ -64,6 +64,34 @@ create or replace noneditionable package ut_metadata authid current_user as function procedure_exists(a_owner_name varchar2, a_package_name in varchar2, a_procedure_name in varchar2) return boolean; + type t_parameter is record ( + procedure_name varchar2(128 char), + overload varchar2(40 char), + parameter_name varchar2(128 char), + defaulted varchar2(1 char), + data_type varchar2(128 char), + type_owner varchar2(128 char), + type_name varchar2(128 char), + type_subname varchar2(128 char) + ); + type tt_parameters is table of t_parameter; + + /** + * Returns the parameters of the procedures of a package (or of one procedure), ordered by procedure, overload and position. + * A procedure or overload without parameters has one entry with a null parameter_name. + */ + function get_package_parameters( + a_owner_name varchar2, a_package_name varchar2, a_procedure_name varchar2 := null + ) return tt_parameters; + + /** + * Returns the return type (data_type, type_owner, type_name) of a packaged function that can be called without arguments, + * or a record with all fields null when there is no such function. + */ + function get_function_return_type( + a_owner_name varchar2, a_package_name varchar2, a_function_name varchar2 + ) return t_parameter; + /** * Return the text of the source line for a given object (body). It excludes package spec and type spec */ diff --git a/source/core/ut_suite_builder.pkb b/source/core/ut_suite_builder.pkb index 0c9bbc982..f8ec76be8 100644 --- a/source/core/ut_suite_builder.pkb +++ b/source/core/ut_suite_builder.pkb @@ -25,6 +25,8 @@ create or replace noneditionable package body ut_suite_builder is gc_suitepath constant t_annotation_name := 'suitepath'; gc_tags constant t_annotation_name := 'tags'; gc_test constant t_annotation_name := ut_utils.gc_test_execute; + gc_testcase constant t_annotation_name := 'testcase'; + gc_testcasesource constant t_annotation_name := 'testcasesource'; gc_disabled constant t_annotation_name := 'disabled'; gc_displayname constant t_annotation_name := 'displayname'; gc_beforeall constant t_annotation_name := ut_utils.gc_before_all; @@ -47,6 +49,8 @@ create or replace noneditionable package body ut_suite_builder is gc_suitepath, gc_tags, gc_test, + gc_testcase, + gc_testcasesource, gc_disabled, gc_displayname, gc_beforeall, @@ -91,7 +95,8 @@ create or replace noneditionable package body ut_suite_builder is parse_time timestamp, by_line tt_annotations_by_line, by_proc tt_annotations_by_proc, - by_name tt_annotations_by_name + by_name tt_annotations_by_name, + parameters ut_metadata.tt_parameters ); procedure delete_annotations_range( @@ -345,6 +350,151 @@ create or replace noneditionable package body ut_suite_builder is end if; end; + -- the parameters of the first overload of a procedure, in order + function get_parameters(a_annotations t_annotations_info, a_procedure_name t_object_name) return ut_metadata.tt_parameters is + l_result ut_metadata.tt_parameters := ut_metadata.tt_parameters(); + l_overload varchar2(40 char); + begin + for i in 1 .. a_annotations.parameters.count loop + if a_annotations.parameters(i).procedure_name = upper(a_procedure_name) then + l_overload := coalesce(l_overload, a_annotations.parameters(i).overload); + if a_annotations.parameters(i).overload = l_overload and a_annotations.parameters(i).parameter_name is not null then + l_result.extend; + l_result(l_result.last) := a_annotations.parameters(i); + end if; + end if; + end loop; + return l_result; + end; + + function get_parameter_names(a_parameters ut_metadata.tt_parameters) return ut_varchar2_list is + l_result ut_varchar2_list := ut_varchar2_list(); + begin + for i in 1 .. a_parameters.count loop + l_result.extend; + l_result(i) := a_parameters(i).parameter_name; + end loop; + return l_result; + end; + + /* + Checks the arguments of a JSON test case (see ut_test_case_json.get_argument_names) against the parameters of the procedure: + number of values, parameter names and parameters without default value. + Types are not checked here; values are converted when the test case runs. + Returns null when the arguments fit one of the overloads, or when the procedure is not known (it is reported when called). + */ + function get_arguments_error( + a_annotations t_annotations_info, + a_procedure_name t_object_name, + a_argument_names ut_varchar2_list + ) return varchar2 is + l_procedure_name t_object_name := upper(a_procedure_name); + l_overload varchar2(40 char); + l_names ut_varchar2_list := ut_varchar2_list(); + l_defaulted ut_varchar2_list := ut_varchar2_list(); + l_error varchar2(4000 char); + l_first_error varchar2(4000 char); + + function get_overload_error return varchar2 is + type tt_given is table of boolean index by t_object_name; + l_given tt_given; + l_name t_object_name; + l_missing varchar2(4000 char); + begin + for i in 1 .. a_argument_names.count loop + l_name := upper(a_argument_names(i)); + if l_name is null then + if i > l_names.count then + return a_argument_names.count || ' value(s) given, but the procedure has ' || l_names.count || ' parameter(s)'; + end if; + l_given(l_names(i)) := true; + else + if not l_name member of l_names then + return 'the procedure has no parameter ' || l_name; + elsif l_given.exists(l_name) then + return 'parameter ' || l_name || ' is given twice'; + end if; + l_given(l_name) := true; + end if; + end loop; + for i in 1 .. l_names.count loop + if l_defaulted(i) = 'N' and not l_given.exists(l_names(i)) then + l_missing := l_missing || case when l_missing is not null then ', ' end || l_names(i); + end if; + end loop; + return case when l_missing is not null then 'no value for parameter(s) ' || l_missing end; + end; + begin + for i in 1 .. a_annotations.parameters.count loop + if a_annotations.parameters(i).procedure_name = l_procedure_name then + if l_overload is not null and l_overload != a_annotations.parameters(i).overload then + l_error := get_overload_error(); + if l_error is null then + return null; + end if; + l_first_error := coalesce(l_first_error, l_error); + l_names := ut_varchar2_list(); + l_defaulted := ut_varchar2_list(); + end if; + l_overload := a_annotations.parameters(i).overload; + -- an overload without parameters has one entry without parameter name + if a_annotations.parameters(i).parameter_name is not null then + l_names.extend; + l_names(l_names.last) := a_annotations.parameters(i).parameter_name; + l_defaulted.extend; + l_defaulted(l_defaulted.last) := a_annotations.parameters(i).defaulted; + end if; + end if; + end loop; + if l_overload is not null then + l_error := get_overload_error(); + return case when l_error is not null then coalesce(l_first_error, l_error) end; + end if; + return null; + end; + + procedure add_test_cases( + a_suite in out nocopy ut_suite, + a_suite_items in out nocopy ut_suite_items, + a_test ut_test, + a_annotations t_annotations_info, + a_test_cases tt_annotation_texts + ) is + l_test ut_test; + l_position t_annotation_position := a_test_cases.first; + l_case_no binary_integer := 0; + l_error varchar2(4000 char); + l_arguments varchar2(4000 char); + l_parameters ut_metadata.tt_parameters := get_parameters(a_annotations, a_test.name); + begin + while l_position is not null loop + -- cases are numbered by annotation, so that the number of a case does not change when another case is invalid + l_case_no := l_case_no + 1; + l_arguments := trim(a_test_cases(l_position)); + l_error := ut_test_case_json.get_json_error(l_arguments); + if l_error is null then + l_error := get_arguments_error(a_annotations, a_test.name, ut_test_case_json.get_argument_names(l_arguments)); + end if; + if l_error is not null then + add_annotation_ignored_warning( + a_suite, gc_testcase, 'Annotation %%% has invalid arguments: ' || l_error || '.', l_position, a_test.name + ); + else + l_test := a_test; + -- each case gets its own cache row, keyed by owner + path and by owner + package + line + l_test.line_no := l_position; + l_test.name := a_test.name || '[' || l_case_no || ']'; + l_test.path := a_test.path || '[' || l_case_no || ']'; + l_test.item.call_arguments := l_arguments; + l_test.description := + ut_test_case_json.get_test_case_description(a_test.description, l_arguments, get_parameter_names(l_parameters)); + a_suite_items.extend; + a_suite_items(a_suite_items.last) := l_test; + end if; + l_position := a_test_cases.next(l_position); + end loop; + end; + procedure add_test( a_suite in out nocopy ut_suite, a_suite_items in out nocopy ut_suite_items, @@ -354,9 +504,22 @@ create or replace noneditionable package body ut_suite_builder is l_test ut_test; l_annotation_texts tt_annotation_texts; l_proc_annotations tt_annotations_by_name := a_annotations.by_proc(a_procedure_name); + l_position t_annotation_position; + c_test_case_annotations constant ut_varchar2_list := ut_varchar2_list(gc_testcase, gc_testcasesource); begin if not l_proc_annotations.exists(gc_test) then + for i in 1 .. c_test_case_annotations.count loop + if l_proc_annotations.exists(c_test_case_annotations(i)) then + l_position := l_proc_annotations(c_test_case_annotations(i)).first; + while l_position is not null loop + add_annotation_ignored_warning( + a_suite, c_test_case_annotations(i), 'Annotation %%% can only be used with "--%test".', l_position, a_procedure_name + ); + l_position := l_proc_annotations(c_test_case_annotations(i)).next(l_position); + end loop; + end if; + end loop; return; end if; warning_on_duplicate_annot( a_suite, l_proc_annotations, gc_test, a_procedure_name); @@ -419,8 +582,31 @@ create or replace noneditionable package body ut_suite_builder is l_test.disabled_reason := l_annotation_texts(l_annotation_texts.first); end if; - a_suite_items.extend; - a_suite_items( a_suite_items.last ) := l_test; + if l_proc_annotations.exists(gc_testcasesource) then + warning_on_duplicate_annot( a_suite, l_proc_annotations, gc_testcasesource, a_procedure_name); + l_annotation_texts := l_proc_annotations(gc_testcasesource); + if l_proc_annotations.exists(gc_testcase) then + add_annotation_ignored_warning( + a_suite, gc_testcasesource, 'Annotation %%% cannot be used together with "--%testcase".', l_annotation_texts.first, a_procedure_name + ); + elsif not nvl(regexp_like( + trim(l_annotation_texts(l_annotation_texts.first)), '^[[:alpha:]][[:alnum:]_$#]*(\.[[:alpha:]][[:alnum:]_$#]*){0,2}$' + ), false) then + add_annotation_ignored_warning( + a_suite, gc_testcasesource, 'Annotation %%% requires the name of a function, e.g. "--%testcasesource(get_test_cases)".', + l_annotation_texts.first, a_procedure_name + ); + else + l_test.item.call_source := trim(l_annotation_texts(l_annotation_texts.first)); + end if; + end if; + + if l_proc_annotations.exists(gc_testcase) then + add_test_cases(a_suite, a_suite_items, l_test, a_annotations, l_proc_annotations(gc_testcase)); + else + a_suite_items.extend; + a_suite_items( a_suite_items.last ) := l_test; + end if; end; @@ -652,6 +838,7 @@ create or replace noneditionable package body ut_suite_builder is l_result.owner := a_annotations.owner; l_result.name := a_annotations.name; l_result.parse_time := a_annotations.parse_time; + l_result.parameters := a_annotations.parameters; while l_position is not null and l_position <= a_end_context_pos loop l_result.by_line(l_position) := a_annotations.by_line(l_position); l_procedure_name := l_result.by_line(l_position).procedure_name; @@ -861,6 +1048,18 @@ create or replace noneditionable package body ut_suite_builder is return l_result; end; + function has_annotation(a_annotations t_annotations_info, a_annotation_name t_annotation_name) return boolean is + l_position t_annotation_position := a_annotations.by_line.first; + begin + while l_position is not null loop + if a_annotations.by_line(l_position).name = a_annotation_name then + return true; + end if; + l_position := a_annotations.by_line.next(l_position); + end loop; + return false; + end; + procedure create_suite_item_list( a_annotated_object ut_annotated_object, a_suite_items out nocopy ut_suite_items ) is l_annotations t_annotations_info; l_annotation_pos t_annotation_position; @@ -873,6 +1072,9 @@ create or replace noneditionable package body ut_suite_builder is l_suite := ut_suite(l_annotations.owner, l_annotations.name, l_annotation_pos); l_suite.description := l_annotations.by_name( gc_suite)( l_annotation_pos); l_suite.parse_time := l_annotations.parse_time; + if has_annotation(l_annotations, gc_testcase) then + l_annotations.parameters := ut_metadata.get_package_parameters(upper(l_annotations.owner), upper(l_annotations.name)); + end if; warning_on_unknown_annotations(l_suite, l_annotations.by_line); warning_on_duplicate_annot( l_suite, l_annotations.by_name, gc_suite ); diff --git a/source/core/ut_suite_cache_macros.pkb b/source/core/ut_suite_cache_macros.pkb index 735b81830..a39ebbf30 100644 --- a/source/core/ut_suite_cache_macros.pkb +++ b/source/core/ut_suite_cache_macros.pkb @@ -29,10 +29,11 @@ create or replace noneditionable package body ut_suite_cache_macros as and i.object_name like replace(replace(upper(p.object_name), '_', '\_'), '*', '%') escape '\' and ( p.procedure_name is null or p.procedure_name = '*' or i.name like replace(replace(upper(p.procedure_name), '_', '\_'), '*', '%') escape '\' + or i.name like replace(replace(upper(p.procedure_name), '_', '\_'), '*', '%') || '[%' escape '\' ) ) or ( instr(p.suite_path, '*') = 0 - and ( i.path = p.suite_path or substr(i.path, 1, length(p.suite_path) + 1) = p.suite_path || '.' ) + and ( i.path = p.suite_path or substr(i.path, 1, length(p.suite_path) + 1) in (p.suite_path || '.', p.suite_path || '[') ) ) or ( instr(p.suite_path, '*') > 0 and regexp_like( diff --git a/source/core/ut_suite_cache_manager.pkb b/source/core/ut_suite_cache_manager.pkb index a3ff6edfd..87c58f307 100644 --- a/source/core/ut_suite_cache_manager.pkb +++ b/source/core/ut_suite_cache_manager.pkb @@ -21,7 +21,7 @@ create or replace noneditionable package body ut_suite_cache_manager is */ function get_schema_paths(a_paths in ut_varchar2_list) return ut_path_items is - c_package_path_regex constant varchar2(100) := '^([[:alnum:]$#_]+)(\.([[:alnum:]$#_\*]+))?(\.([[:alnum:]$#_\*]+))?$'; + c_package_path_regex constant varchar2(100) := '^([[:alnum:]$#_]+)(\.([[:alnum:]$#_\*]+))?(\.([[:alnum:]$#_\*]+(\[[0-9]+\])?))?$'; l_results ut_path_items := ut_path_items(); l_path_item ut_path_item; i pls_integer; @@ -430,7 +430,7 @@ create or replace noneditionable package body ut_suite_cache_manager is from &&ut3_owner..ut_suite_cache c where c.object_owner = a_owner_name and c.object_name = a_package_name - and c.name = a_procedure_name + and ( c.name = a_procedure_name or substr(c.name, 1, length(a_procedure_name) + 1) = a_procedure_name || '[' ) ); elsif a_package_name is not null then select /*+ no_parallel */ count( 1 ) into l_count from dual diff --git a/source/core/ut_suite_manager.pkb b/source/core/ut_suite_manager.pkb index 3689d991e..e2eee4288 100644 --- a/source/core/ut_suite_manager.pkb +++ b/source/core/ut_suite_manager.pkb @@ -31,7 +31,9 @@ create or replace noneditionable package body ut_suite_manager is for i in 1 .. a_paths.count loop l_path := a_paths(i); if l_path is null or not ( - regexp_like(l_path, '^[[:alnum:]$#_\*]+(\.[[:alnum:]$#_\*]+){0,2}$') or regexp_like(l_path, '^([[:alnum:]$#_]+)?:[[:alnum:]$#_\*]+(\.[[:alnum:]$#_\*]+)*$')) then + regexp_like(l_path, '^[[:alnum:]$#_\*]+(\.[[:alnum:]$#_\*]+){0,2}$') + or regexp_like(l_path, '^[[:alnum:]$#_\*]+(\.[[:alnum:]$#_\*]+){1,2}\[[0-9]+\]$') + or regexp_like(l_path, '^([[:alnum:]$#_]+)?:[[:alnum:]$#_\*]+(\.[[:alnum:]$#_\*]+)*(\[[0-9]+\])?$')) then raise_application_error(ut_utils.gc_invalid_path_format, 'Invalid path format: ' || nvl(l_path, 'NULL')); end if; end loop; @@ -89,6 +91,10 @@ create or replace noneditionable package body ut_suite_manager is end if; end; end if; + if a_paths(i) not like '%:%' and instr(a_paths(i), '[') > 0 + and not regexp_like(a_paths(i), '^[^.]+\.[^.]+\.[^.]+\[[0-9]+\]$') then + raise_application_error(ut_utils.gc_invalid_path_format, 'Invalid path format: ' || a_paths(i)); + end if; l_schema_names.extend; l_schema_names(l_schema_names.last) := l_schema; end loop; diff --git a/source/core/ut_test_case_json.pkb b/source/core/ut_test_case_json.pkb new file mode 100644 index 000000000..086d1a4a5 --- /dev/null +++ b/source/core/ut_test_case_json.pkb @@ -0,0 +1,328 @@ +create or replace noneditionable package body ut_test_case_json as + /* + utPLSQL - Version 3 + Copyright 2016 - 2026 utPLSQL Project + + Licensed 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. + */ + + procedure raise_invalid(a_message varchar2) is + begin + raise_application_error(ut_utils.gc_invalid_test_case_source, 'Invalid JSON test case: ' || a_message || '.'); + end; + + function get_json_error(a_json clob) return varchar2 is + l_element json_element_t; + begin + -- an annotation is a single line, so only spaces and tabs can precede the JSON + if nvl(substr(ltrim(a_json, ' ' || chr(9)), 1, 1) not in ('[', '{'), true) then + return 'a JSON array or object is expected'; + end if; + -- text that starts with [ or { is a JSON array or object when it can be parsed + l_element := json_element_t.parse(a_json); + return null; + exception + when others then + return 'it is not valid JSON'; + end; + + procedure get_names_and_values( + a_json clob, a_names out nocopy ut_varchar2_list, a_values out nocopy ut_varchar2_list, a_parameter_names ut_varchar2_list := null + ) is + l_element json_element_t := json_element_t.parse(a_json); + l_array json_array_t; + l_object json_object_t; + l_keys json_key_list; + + -- strings are shown without quotes; only the start of long values is shown + function display_value(a_value json_element_t, a_string clob) return varchar2 is + begin + return dbms_lob.substr( + case when a_value.is_string then a_string when a_value.is_null then to_clob('null') else a_value.to_clob end, + ut_utils.gc_max_storage_varchar2_len + ); + end; + begin + a_names := ut_varchar2_list(); + a_values := ut_varchar2_list(); + if l_element.is_array then + l_array := treat(l_element as json_array_t); + for i in 0 .. l_array.get_size - 1 loop + a_names.extend; + -- values passed by position get the name of their parameter, so the description can refer to them by name + if i < cardinality(a_parameter_names) then + a_names(a_names.last) := lower(a_parameter_names(i + 1)); + end if; + a_values.extend; + a_values(a_values.last) := display_value(l_array.get(i), case when l_array.get(i).is_string then l_array.get_clob(i) end); + end loop; + else + l_object := treat(l_element as json_object_t); + l_keys := l_object.get_keys; + for i in 1 .. l_keys.count loop + a_names.extend; + a_names(a_names.last) := l_keys(i); + a_values.extend; + a_values(a_values.last) := display_value( + l_object.get(l_keys(i)), case when l_object.get(l_keys(i)).is_string then l_object.get_clob(l_keys(i)) end + ); + end loop; + end if; + end; + + function get_argument_names(a_json clob) return ut_varchar2_list is + l_names ut_varchar2_list; + l_values ut_varchar2_list; + begin + get_names_and_values(a_json, l_names, l_values); + return l_names; + end; + + function get_test_case_description( + a_description varchar2, a_json clob, a_parameter_names ut_varchar2_list := null + ) return varchar2 is + l_names ut_varchar2_list; + l_values ut_varchar2_list; + begin + get_names_and_values(a_json, l_names, l_values, a_parameter_names); + return ut_utils.get_test_case_description(a_description, l_names, l_values); + end; + + function get_call(a_owner varchar2, a_package varchar2, a_procedure varchar2, a_call_name varchar2, a_json clob) return varchar2 is + type tt_names is table of varchar2(30 char) index by varchar2(400 char); + l_all_parameters ut_metadata.tt_parameters := + ut_metadata.get_package_parameters(upper(a_owner), upper(a_package), upper(a_procedure)); + l_parameters ut_metadata.tt_parameters := ut_metadata.tt_parameters(); + l_element json_element_t := json_element_t.parse(a_json); + l_array json_array_t; + l_keys json_key_list; + l_case_type varchar2(30 char); + l_count binary_integer := 0; + l_declarations varchar2(32767); + l_functions varchar2(32767); + l_assignments varchar2(32767); + l_arguments varchar2(32767); + l_given ut_varchar2_list := ut_varchar2_list(); + l_index pls_integer; + -- each type is converted by one generated function + l_converters tt_names; + c_error constant varchar2(30 char) := to_char(ut_utils.gc_invalid_test_case_source); + + procedure raise_unsupported(a_parameter ut_metadata.t_parameter) is + begin + raise_invalid( + 'parameter ' || a_parameter.parameter_name || ' has a data type that can''t be passed from JSON: ' + || nvl(a_parameter.type_name || case when a_parameter.type_subname is not null then '.' || a_parameter.type_subname end, a_parameter.data_type) + ); + end; + + -- the declaration of a variable of the parameter type, and how json_value returns it; null when it can't be passed from JSON + procedure get_type(a_parameter ut_metadata.t_parameter, a_declaration out varchar2, a_returning out varchar2) is + l_type varchar2(128 char) := a_parameter.data_type; + begin + case + when l_type in ('NUMBER', 'FLOAT', 'BINARY_INTEGER') then + a_declaration := 'number'; + a_returning := 'number'; + when l_type in ('BINARY_FLOAT', 'BINARY_DOUBLE') then + a_declaration := lower(l_type); + a_returning := 'number'; + when l_type in ('VARCHAR2', 'CHAR') then + a_declaration := 'varchar2(32767)'; + a_returning := 'clob'; + when l_type in ('NVARCHAR2', 'NCHAR') then + a_declaration := 'nvarchar2(32767)'; + a_returning := 'clob'; + when l_type in ('CLOB', 'NCLOB') then + a_declaration := lower(l_type); + a_returning := 'clob'; + when l_type in ('DATE', 'TIMESTAMP', 'TIMESTAMP WITH TIME ZONE', 'TIMESTAMP WITH LOCAL TIME ZONE') then + -- read as text and converted with ut_utils.gc_test_case_timestamp_format, independent of the NLS settings + a_declaration := replace(lower(l_type), 'timestamp', 'timestamp(9)'); + a_returning := 'varchar2(100)'; + when l_type = 'INTERVAL DAY TO SECOND' then + a_declaration := 'interval day(9) to second(9)'; + a_returning := 'varchar2(100)'; + when l_type = 'INTERVAL YEAR TO MONTH' then + a_declaration := 'interval year(9) to month'; + a_returning := 'varchar2(100)'; + when l_type = 'RAW' then + a_declaration := 'raw(32767)'; + a_returning := 'varchar2(4000)'; + when l_type in ('BOOLEAN', 'PL/SQL BOOLEAN') then + a_declaration := 'boolean'; + when l_type in ('OBJECT', 'TABLE', 'VARRAY') and a_parameter.type_subname is null and a_parameter.type_owner != 'PUBLIC' then + a_declaration := '"' || a_parameter.type_owner || '"."' || a_parameter.type_name || '"'; + -- error on mismatch: a missing or misspelled attribute is an error instead of a null attribute + a_returning := a_declaration || ' error on error error on mismatch'; + else + null; + end case; + end; + + -- a call of the generated function that converts the JSON element a_value to the type of the parameter + function convert(a_parameter ut_metadata.t_parameter, a_value varchar2) return varchar2 is + l_key varchar2(400 char) := a_parameter.data_type || '.' || a_parameter.type_owner || '.' || a_parameter.type_name; + l_function varchar2(30 char); + l_declaration varchar2(400 char); + l_returning varchar2(400 char); + l_value varchar2(400 char); + begin + if not l_converters.exists(l_key) then + get_type(a_parameter, l_declaration, l_returning); + if l_declaration is null then + raise_unsupported(a_parameter); + end if; + l_function := 'ut_convert_' || (l_converters.count + 1); + l_converters(l_key) := l_function; + if l_declaration = 'boolean' then + -- SQL has no BOOLEAN before Oracle 23, so it is read with the PL/SQL JSON API + l_functions := l_functions || + ' function ' || l_function || '(a_value json_element_t) return boolean is' || chr(10) || + ' begin' || chr(10) || + ' if a_value is null or a_value.is_null then' || chr(10) || + ' return null;' || chr(10) || + ' elsif a_value.is_true then' || chr(10) || + ' return true;' || chr(10) || + ' elsif a_value.is_false then' || chr(10) || + ' return false;' || chr(10) || + ' end if;' || chr(10) || + ' raise_application_error(' || c_error || ', ''Invalid JSON test case: true or false expected instead of '' || a_value.to_string || ''.'');' || chr(10) || + ' end;' || chr(10); + else + l_value := 'json_value(l_json, ''$[0]'' returning ' || l_returning || case when l_returning not like '% error on error%' then ' error on error' end || ')'; + l_value := + case + when a_parameter.data_type in ('DATE', 'TIMESTAMP', 'TIMESTAMP WITH TIME ZONE', 'TIMESTAMP WITH LOCAL TIME ZONE') then + 'to_timestamp_tz(' || l_value || ', ''' || ut_utils.gc_test_case_timestamp_format || ''')' + when a_parameter.data_type = 'INTERVAL DAY TO SECOND' then 'to_dsinterval(' || l_value || ')' + when a_parameter.data_type = 'INTERVAL YEAR TO MONTH' then 'to_yminterval(' || l_value || ')' + when a_parameter.data_type = 'RAW' then 'hextoraw(' || l_value || ')' + else l_value + end; + l_functions := l_functions || + ' function ' || l_function || '(a_value json_element_t) return ' || regexp_replace(l_declaration, '\([0-9]+\)') || ' is' || chr(10) || + ' l_array json_array_t := json_array_t();' || chr(10) || + ' l_json clob;' || chr(10) || + ' l_result ' || l_declaration || ';' || chr(10) || + ' begin' || chr(10) || + ' if a_value is null or a_value.is_null then' || chr(10) || + ' return null;' || chr(10) || + ' end if;' || chr(10) || + -- json_value converts a scalar to an object or collection with all attributes null, so that is checked here + case + when a_parameter.data_type = 'OBJECT' then + ' if not a_value.is_object then' || chr(10) || + ' raise_application_error(' || c_error || ', ''Invalid JSON test case: a JSON object expected instead of '' || a_value.to_string || ''.'');' || chr(10) || + ' end if;' || chr(10) + when a_parameter.data_type in ('TABLE', 'VARRAY') then + ' if not a_value.is_array then' || chr(10) || + ' raise_application_error(' || c_error || ', ''Invalid JSON test case: a JSON array expected instead of '' || a_value.to_string || ''.'');' || chr(10) || + ' end if;' || chr(10) + end || + -- json_value reads from a JSON document, so the value is wrapped in an array + ' l_array.append(a_value);' || chr(10) || + ' l_json := l_array.to_clob;' || chr(10) || + ' select ' || l_value || ' into l_result from dual;' || chr(10) || + ' return l_result;' || chr(10) || + ' end;' || chr(10); + end if; + end if; + return l_converters(l_key) || '(' || a_value || ')'; + end; + + procedure add_argument(a_parameter ut_metadata.t_parameter, a_accessor varchar2) is + l_variable varchar2(30 char); + l_declaration varchar2(400 char); + l_returning varchar2(400 char); + begin + l_count := l_count + 1; + l_variable := 'l_ut_arg_' || l_count; + get_type(a_parameter, l_declaration, l_returning); + l_assignments := l_assignments || ' ' || l_variable || ' := ' || convert(a_parameter, 'l_ut_case.get(' || a_accessor || ')') || ';' || chr(10); + l_declarations := l_declarations || ' ' || l_variable || ' ' || l_declaration || ';' || chr(10); + l_arguments := l_arguments || case when l_arguments is not null then ', ' end || '"' || a_parameter.parameter_name || '" => ' || l_variable; + end; + + -- a key that is no parameter is an error, not ignored, so that a misspelled key doesn't silently leave + -- a parameter at its default (decided in #1326) + function find_parameter(a_key varchar2) return ut_metadata.t_parameter is + l_result ut_metadata.t_parameter; + begin + for i in 1 .. l_parameters.count loop + if l_parameters(i).parameter_name = upper(a_key) then + l_result := l_parameters(i); + end if; + end loop; + if l_result.parameter_name is null then + raise_invalid('the procedure has no parameter ' || a_key); + end if; + return l_result; + end; + begin + for i in 1 .. l_all_parameters.count loop + if l_all_parameters(i).overload != l_all_parameters(1).overload then + raise_invalid('JSON test cases can''t be used with the overloaded procedure ' || upper(a_procedure)); + end if; + if l_all_parameters(i).parameter_name is not null then + l_parameters.extend; + l_parameters(l_parameters.last) := l_all_parameters(i); + end if; + end loop; + + if l_element.is_array then + l_case_type := 'json_array_t'; + l_array := treat(l_element as json_array_t); + if l_array.get_size > l_parameters.count then + raise_invalid(l_array.get_size || ' value(s) given, but the procedure has ' || l_parameters.count || ' parameter(s)'); + end if; + for i in 0 .. l_array.get_size - 1 loop + add_argument(l_parameters(i + 1), to_char(i)); + l_given.extend; + l_given(l_given.last) := l_parameters(i + 1).parameter_name; + end loop; + else + -- only JSON arrays and objects get here, see get_json_error and ut_test.get_source_test_cases + l_case_type := 'json_object_t'; + l_keys := treat(l_element as json_object_t).get_keys; + for i in 1 .. l_keys.count loop + if upper(l_keys(i)) member of l_given then + raise_invalid('parameter ' || upper(l_keys(i)) || ' is given twice'); + end if; + l_given.extend; + l_given(l_given.last) := upper(l_keys(i)); + -- the key matches a parameter name, so it can be used in a string literal as it is + add_argument(find_parameter(l_keys(i)), '''' || l_keys(i) || ''''); + end loop; + end if; + l_index := l_parameters.first; + while l_index is not null loop + if l_parameters(l_index).defaulted = 'N' and not l_parameters(l_index).parameter_name member of l_given then + raise_invalid('no value for parameter ' || l_parameters(l_index).parameter_name || ', which has no default value'); + end if; + l_index := l_parameters.next(l_index); + end loop; + + return + 'declare' || chr(10) || + ' l_ut_case ' || l_case_type || ' := ' || l_case_type || '.parse(:ut_json);' || chr(10) || + l_declarations || + l_functions || + 'begin' || chr(10) || + l_assignments || + ' ' || a_call_name || case when l_arguments is not null then '(' || l_arguments || ')' end || ';' || chr(10) || + 'end;'; + end; + +end; +/ diff --git a/source/core/ut_test_case_json.pks b/source/core/ut_test_case_json.pks new file mode 100644 index 000000000..84626818e --- /dev/null +++ b/source/core/ut_test_case_json.pks @@ -0,0 +1,48 @@ +create or replace noneditionable package ut_test_case_json authid current_user as + /* + utPLSQL - Version 3 + Copyright 2016 - 2026 utPLSQL Project + + Licensed 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. + */ + + /** + * Test cases given as JSON, by --%testcase or by a --%testcasesource function: + * a JSON array passes its values by position, a JSON object passes its values to the parameters named like its keys. + */ + + /** + * Returns the reason why a text can't be the arguments of a test case (a JSON array or object), or null when it can. + */ + function get_json_error(a_json clob) return varchar2; + + /** + * Returns the keys of a JSON object, or for a JSON array one null per value (passed by position), + * so that a test case can be checked against the parameters of the procedure (see ut_suite_builder). + */ + function get_argument_names(a_json clob) return ut_varchar2_list; + + /** + * Returns the description of a JSON test case, with the values of the test case filled in (see ut_utils.get_test_case_description). + * Values of a JSON array can be referred to by the names of the parameters they are passed to, given in a_parameter_names. + */ + function get_test_case_description(a_description varchar2, a_json clob, a_parameter_names ut_varchar2_list := null) return varchar2; + + /** + * Returns a PL/SQL block that calls the procedure with the values of a JSON test case, converted to the types of its parameters. + * The block expects the JSON text as bind variable :ut_json. + */ + function get_call(a_owner varchar2, a_package varchar2, a_procedure varchar2, a_call_name varchar2, a_json clob) return varchar2; + +end; +/ diff --git a/source/core/ut_test_case_values.pkb b/source/core/ut_test_case_values.pkb new file mode 100644 index 000000000..9592b0832 --- /dev/null +++ b/source/core/ut_test_case_values.pkb @@ -0,0 +1,51 @@ +create or replace noneditionable package body ut_test_case_values as + /* + utPLSQL - Version 3 + Copyright 2016 - 2026 utPLSQL Project + + Licensed 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. + */ + + type tt_values is table of ut_anydata_list index by varchar2(4000 char); + type tt_json is table of clob index by varchar2(4000 char); + g_values tt_values; + g_json tt_json; + + procedure set_values(a_test_path varchar2, a_values ut_anydata_list) is + begin + g_values(a_test_path) := a_values; + end; + + function get_values(a_test_path varchar2) return ut_anydata_list is + begin + return case when g_values.exists(a_test_path) then g_values(a_test_path) end; + end; + + procedure set_json(a_test_path varchar2, a_json clob) is + begin + g_json(a_test_path) := a_json; + end; + + function get_json(a_test_path varchar2) return clob is + begin + return case when g_json.exists(a_test_path) then g_json(a_test_path) end; + end; + + procedure remove_values(a_test_path varchar2) is + begin + g_values.delete(a_test_path); + g_json.delete(a_test_path); + end; + +end; +/ diff --git a/source/core/ut_test_case_values.pks b/source/core/ut_test_case_values.pks new file mode 100644 index 000000000..b67e2ed83 --- /dev/null +++ b/source/core/ut_test_case_values.pks @@ -0,0 +1,37 @@ +create or replace noneditionable package ut_test_case_values authid definer as + /* + utPLSQL - Version 3 + Copyright 2016 - 2026 utPLSQL Project + + Licensed 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. + */ + + /** + * Holds the argument values of --%testcasesource test cases from the moment a test is split into its + * test cases until each test case has run: the row values of a cursor as ANYDATA, or the JSON text of a JSON test case. + * The values can't be attributes of the suite item types, as those types are stored and queried with SQL, + * which doesn't allow ANYDATA in collections, and the JSON text can be longer than a varchar2 attribute. + */ + + procedure set_values(a_test_path varchar2, a_values ut_anydata_list); + + function get_values(a_test_path varchar2) return ut_anydata_list; + + procedure set_json(a_test_path varchar2, a_json clob); + + function get_json(a_test_path varchar2) return clob; + + procedure remove_values(a_test_path varchar2); + +end; +/ diff --git a/source/core/ut_utils.pkb b/source/core/ut_utils.pkb index 865e9e17c..2e39bb3f6 100644 --- a/source/core/ut_utils.pkb +++ b/source/core/ut_utils.pkb @@ -232,6 +232,31 @@ create or replace noneditionable package body ut_utils is return l_result; end; + function get_test_case_description( + a_description varchar2, a_names ut_varchar2_list, a_values ut_varchar2_list + ) return varchar2 is + c_max_value_length constant integer := 100; + l_result varchar2(32767) := a_description; + l_appendix varchar2(32767); + l_value varchar2(32767); + begin + for i in 1 .. a_values.count loop + -- long values would make the description unreadable + l_value := substr(a_values(i), 1, c_max_value_length) || case when length(a_values(i)) > c_max_value_length then '...' end; + l_appendix := l_appendix || case when i > 1 then ', ' end || l_value; + if regexp_like(a_description, '\{[[:alnum:]_$#]+\}') then + l_result := replace(l_result, '{' || i || '}', l_value); + if a_names(i) is not null then + l_result := replace(replace(l_result, '{' || a_names(i) || '}', l_value), '{' || lower(a_names(i)) || '}', l_value); + end if; + end if; + end loop; + if not regexp_like(a_description, '\{[[:alnum:]_$#]+\}') then + l_result := a_description || case when a_description is not null and l_appendix is not null then ' (' || l_appendix || ')' end; + end if; + return substrb(l_result, 1, gc_max_storage_varchar2_len); + end; + function string_table_to_table(a_list ut_varchar2_list, a_delimiter varchar2:= chr(10), a_skip_leading_delimiter varchar2 := 'N') return ut_varchar2_list is l_result ut_varchar2_list; begin diff --git a/source/core/ut_utils.pks b/source/core/ut_utils.pks index ad762d123..800404354 100644 --- a/source/core/ut_utils.pks +++ b/source/core/ut_utils.pks @@ -125,6 +125,10 @@ create or replace noneditionable package ut_utils authid definer is ex_invalid_tag_expression exception; gc_invalid_tag_expression constant pls_integer := -20219; pragma exception_init (ex_invalid_tag_expression, -20219); + + -- the query of a --%testcasesource annotation returns a column that can't be passed to the test + gc_invalid_test_case_source constant pls_integer := -20220; + gc_max_storage_varchar2_len constant integer := 4000; gc_max_output_string_length constant integer := 4000; @@ -134,6 +138,8 @@ create or replace noneditionable package ut_utils authid definer is gc_date_format constant varchar2(100) := 'syyyy-mm-dd"T"hh24:mi:ss'; gc_timestamp_format constant varchar2(100) := 'syyyy-mm-dd"T"hh24:mi:ssxff'; gc_timestamp_tz_format constant varchar2(100) := 'syyyy-mm-dd"T"hh24:mi:ssxff tzh:tzm'; + -- the format of date and time strings in test cases (--%testcase, --%testcasesource); a fixed decimal point, unlike gc_timestamp_format + gc_test_case_timestamp_format constant varchar2(100) := 'syyyy-mm-dd"T"hh24:mi:ss.ff tzh:tzm'; gc_null_string constant varchar2(4) := 'NULL'; gc_empty_string constant varchar2(5) := 'EMPTY'; @@ -235,6 +241,21 @@ create or replace noneditionable package ut_utils authid definer is */ function string_to_table(a_string varchar2, a_delimiter varchar2:= chr(10), a_skip_leading_delimiter varchar2 := 'N') return ut_varchar2_list; + /** + * + * Builds the description of a test case of a --%testcase or --%testcasesource test. + * {1}, {2}, ... in the description are replaced with the values, {} with the value of that name. + * Without placeholders, the values separated by commas are appended in brackets. A null description stays null. + * Values longer than 100 characters are shortened. + * + * @param a_description the description of the test + * @param a_names names of the values (parameter or column names), elements may be null + * @param a_values the values, as shown in the description + */ + function get_test_case_description( + a_description varchar2, a_names ut_varchar2_list, a_values ut_varchar2_list + ) return varchar2; + /** * * Splits each string in table of string into a table of string using specified delimiter. diff --git a/source/create_grants.sql b/source/create_grants.sql index 5cf7cfaaa..63e5a8ed0 100644 --- a/source/create_grants.sql +++ b/source/create_grants.sql @@ -73,6 +73,7 @@ grant execute on &&ut3_owner..ut_suite_cache_macros to &ut3_user; --generic types grant execute on &&ut3_owner..ut_varchar2_list to &ut3_user; grant execute on &&ut3_owner..ut_varchar2_rows to &ut3_user; +grant execute on &&ut3_owner..ut_anydata_list to &ut3_user; grant execute on &&ut3_owner..ut_integer_list to &ut3_user; grant execute on &&ut3_owner..ut_key_value_pairs to &ut3_user; grant execute on &&ut3_owner..ut_key_value_pair to &ut3_user; diff --git a/source/install.sql b/source/install.sql index 3feca3a7d..8f05490a2 100644 --- a/source/install.sql +++ b/source/install.sql @@ -45,6 +45,7 @@ create or replace context &&ut3_owner._info using &&ut3_owner..ut_session_contex -- spec @@install_component.sql 'core/types/ut_varchar2_list.tps' @@install_component.sql 'core/types/ut_varchar2_rows.tps' +@@install_component.sql 'core/types/ut_anydata_list.tps' @@install_component.sql 'core/types/ut_integer_list.tps' @@install_component.sql 'core/types/ut_object_name.tps' @@install_component.sql 'core/types/ut_object_names.tps' @@ -55,6 +56,8 @@ create or replace context &&ut3_owner._info using &&ut3_owner..ut_session_contex @@install_component.sql 'core/types/ut_stack.tps' @@install_component.sql 'core/ut_utils.pks' @@install_component.sql 'core/ut_metadata.pks' +@@install_component.sql 'core/ut_test_case_values.pks' +@@install_component.sql 'core/ut_test_case_json.pks' @@install_component.sql 'core/ut_savepoint_seq.sql' @@install_component.sql 'reporters/ut_ansiconsole_helper.pks' @@install_component.sql 'api/ut_suite_item_info.tps' @@ -64,6 +67,8 @@ create or replace context &&ut3_owner._info using &&ut3_owner..ut_session_contex @@install_component.sql 'core/types/ut_stack.tpb' @@install_component.sql 'core/ut_utils.pkb' @@install_component.sql 'core/ut_metadata.pkb' +@@install_component.sql 'core/ut_test_case_values.pkb' +@@install_component.sql 'core/ut_test_case_json.pkb' @@install_component.sql 'reporters/ut_ansiconsole_helper.pkb' @@install_component.sql 'api/ut_suite_item_info.tpb' diff --git a/source/reporters/ut_junit_reporter.tpb b/source/reporters/ut_junit_reporter.tpb index e7741926d..b767bc5bd 100644 --- a/source/reporters/ut_junit_reporter.tpb +++ b/source/reporters/ut_junit_reporter.tpb @@ -29,7 +29,10 @@ create or replace noneditionable type body ut_junit_reporter is function get_path(a_path_with_name varchar2, a_name varchar2) return varchar2 is begin - return regexp_substr(a_path_with_name, '(.*)\.' ||a_name||'$',subexpression=>1); + if substr(a_path_with_name, -length(a_name) - 1) = '.' || a_name then + return substr(a_path_with_name, 1, length(a_path_with_name) - length(a_name) - 1); + end if; + return null; end; procedure print_test_elements(a_test ut_test) is diff --git a/source/reporters/ut_teamcity_reporter.tpb b/source/reporters/ut_teamcity_reporter.tpb index 2e76e3e3f..ec3a3c096 100644 --- a/source/reporters/ut_teamcity_reporter.tpb +++ b/source/reporters/ut_teamcity_reporter.tpb @@ -45,7 +45,7 @@ create or replace noneditionable type body ut_teamcity_reporter is begin l_test_full_name := lower(a_test.item.owner_name) || '.' || lower(a_test.item.object_name) || '.' || - lower(a_test.item.procedure_name); + lower(a_test.name); self.print_text( ut_teamcity_reporter_helper.test_started( @@ -81,7 +81,7 @@ create or replace noneditionable type body ut_teamcity_reporter is end; begin l_test_full_name := lower(a_test.item.owner_name) || '.' || lower(a_test.item.object_name) || '.' || - lower(a_test.item.procedure_name); + lower(a_test.name); if a_test.result = ut_utils.gc_disabled then ut_utils.append_to_list( l_results, ut_teamcity_reporter_helper.test_disabled(l_test_full_name,a_test.disabled_reason)); diff --git a/source/reporters/ut_tfs_junit_reporter.tpb b/source/reporters/ut_tfs_junit_reporter.tpb index 38aa41bfa..75b4f8010 100644 --- a/source/reporters/ut_tfs_junit_reporter.tpb +++ b/source/reporters/ut_tfs_junit_reporter.tpb @@ -48,7 +48,10 @@ create or replace noneditionable type body ut_tfs_junit_reporter is function get_path(a_path_with_name varchar2, a_name varchar2) return varchar2 is begin - return regexp_substr(a_path_with_name, '(.*)\.' ||a_name||'$',subexpression=>1); + if substr(a_path_with_name, -length(a_name) - 1) = '.' || a_name then + return substr(a_path_with_name, 1, length(a_path_with_name) - length(a_name) - 1); + end if; + return null; end; function add_test_results(a_test ut_test) return ut_varchar2_rows is diff --git a/source/uninstall_objects.sql b/source/uninstall_objects.sql index 5c6e41dc3..95c200afb 100644 --- a/source/uninstall_objects.sql +++ b/source/uninstall_objects.sql @@ -270,6 +270,10 @@ drop package ut_file_mapper; drop package ut_metadata; +drop package ut_test_case_values; + +drop package ut_test_case_json; + drop package ut_ansiconsole_helper; begin @@ -400,6 +404,8 @@ drop type ut_varchar2_list force; drop type ut_varchar2_rows force; +drop type ut_anydata_list force; + drop package ut_coverage_profiler; drop package ut_compound_data_helper; diff --git a/test/install_ut3_user_tests.sql b/test/install_ut3_user_tests.sql index 36966b3f6..c1e7e02fb 100644 --- a/test/install_ut3_user_tests.sql +++ b/test/install_ut3_user_tests.sql @@ -33,6 +33,7 @@ prompt Install user tests @@ut3_user/expectations/test_expectations_json.pks @@ut3_user/api/test_ut_runner.pks @@ut3_user/api/test_ut_run.pks +@@ut3_user/api/test_ut_test_cases.pks @@ut3_user/reporters.pks @@ut3_user/reporters/test_tfs_junit_reporter.pks @@ut3_user/reporters/test_teamcity_reporter.pks @@ -74,6 +75,7 @@ set define off @@ut3_user/expectations/test_expectations_json.pkb @@ut3_user/api/test_ut_runner.pkb @@ut3_user/api/test_ut_run.pkb +@@ut3_user/api/test_ut_test_cases.pkb @@ut3_user/reporters.pkb @@ut3_user/reporters/test_tfs_junit_reporter.pkb @@ut3_user/reporters/test_teamcity_reporter.pkb diff --git a/test/ut3_tester/core/test_suite_builder.pkb b/test/ut3_tester/core/test_suite_builder.pkb index 15aac2d01..71a4375c3 100644 --- a/test/ut3_tester/core/test_suite_builder.pkb +++ b/test/ut3_tester/core/test_suite_builder.pkb @@ -1968,5 +1968,232 @@ create or replace package body test_suite_builder is ); end; + procedure testcase_creates_test_per_case is + l_actual clob; + l_annotations ut3_develop.ut_annotations; + begin + --Arrange + l_annotations := ut3_develop.ut_annotations( + ut3_develop.ut_annotation(1, 'suite','Cool', null), + ut3_develop.ut_annotation(14, 'test','A test', 'some_test'), + ut3_develop.ut_annotation(15, 'testcase', '[2000, "a, b"]', 'some_test'), + ut3_develop.ut_annotation(16, 'testcase', '{"a_amount": 1}', 'some_test'), + ut3_develop.ut_annotation(17, 'tags', 'fast', 'some_test') + ); + --Act + l_actual := invoke_builder_for_annotations(l_annotations, 'SOME_PACKAGE'); + --Assert + ut.expect(l_actual).to_be_like( + '%%some_test[1]' || + '%A test (2000, a, b)some_package.some_test[1]' || + '%15%fast' || + '%some_test%[2000, "a, b"]' || + '%' || + '%%some_test[2]' || + '%some_package.some_test[2]' || + '%16%fast' || + '%{"a_amount": 1}' || + '%%' + ); + ut.expect(l_actual).not_to_be_like('%some_package.some_test%'); + end; + + procedure testcase_description_placeholders is + l_actual clob; + l_annotations ut3_develop.ut_annotations; + begin + --Arrange + l_annotations := ut3_develop.ut_annotations( + ut3_develop.ut_annotation(1, 'suite','Cool', null), + ut3_develop.ut_annotation(14, 'test','Amount {1}, kind {a_kind}, unknown {3}', 'some_test'), + ut3_develop.ut_annotation(15, 'testcase', '{"a_amount": 100, "a_kind": "VIP"}', 'some_test') + ); + --Act + l_actual := invoke_builder_for_annotations(l_annotations, 'SOME_PACKAGE'); + --Assert + ut.expect(l_actual).to_be_like( + '%Amount 100, kind VIP, unknown {3}some_package.some_test[1]%' + ); + end; + + procedure testcase_without_test is + l_actual clob; + l_annotations ut3_develop.ut_annotations; + begin + --Arrange + l_annotations := ut3_develop.ut_annotations( + ut3_develop.ut_annotation(1, 'suite','Cool', null), + ut3_develop.ut_annotation(15, 'testcase', '[1]', 'some_procedure') + ); + --Act + l_actual := invoke_builder_for_annotations(l_annotations, 'SOME_PACKAGE'); + --Assert + ut.expect(l_actual).to_be_like( + '%%Annotation "--%testcase" can only be used with "--%test". Annotation ignored.%%' + ); + ut.expect(l_actual).not_to_be_like('%%'); + end; + + procedure testcasesource_stores_query is + l_actual clob; + l_annotations ut3_develop.ut_annotations; + begin + --Arrange + l_annotations := ut3_develop.ut_annotations( + ut3_develop.ut_annotation(1, 'suite','Cool', null), + ut3_develop.ut_annotation(14, 'test','A test', 'some_test'), + ut3_develop.ut_annotation(15, 'testcasesource', 'other_package.get_cases', 'some_test') + ); + --Act + l_actual := invoke_builder_for_annotations(l_annotations, 'SOME_PACKAGE'); + --Assert + ut.expect(l_actual).to_be_like( + '%%some_test%some_package.some_test' || + '%other_package.get_cases%%' + ); + end; + + procedure testcasesource_invalid_use is + l_actual clob; + l_annotations ut3_develop.ut_annotations; + begin + --Arrange + l_annotations := ut3_develop.ut_annotations( + ut3_develop.ut_annotation(1, 'suite','Cool', null), + ut3_develop.ut_annotation(14, 'test','Both', 'both_test'), + ut3_develop.ut_annotation(15, 'testcase', '[1]', 'both_test'), + ut3_develop.ut_annotation(16, 'testcasesource', 'get_cases', 'both_test'), + ut3_develop.ut_annotation(20, 'test','No function', 'no_function_test'), + ut3_develop.ut_annotation(21, 'testcasesource', null, 'no_function_test'), + ut3_develop.ut_annotation(22, 'test','Query', 'query_test'), + ut3_develop.ut_annotation(23, 'testcasesource', 'select 1 from dual', 'query_test'), + ut3_develop.ut_annotation(25, 'testcasesource', 'get_cases', 'not_a_test') + ); + --Act + l_actual := invoke_builder_for_annotations(l_annotations, 'SOME_PACKAGE'); + --Assert + ut.expect(l_actual).to_be_like( + '%' || + '%Annotation "--%testcasesource" cannot be used together with "--%testcase". Annotation ignored.' || + '%Annotation "--%testcasesource" requires the name of a function, e.g. "--%testcasesource(get_test_cases)". Annotation ignored.' || + '%Annotation "--%testcasesource" can only be used with "--%test". Annotation ignored.' || + '%Annotation "--%testcasesource" requires the name of a function, e.g. "--%testcasesource(get_test_cases)". Annotation ignored.' || + '%%' + ); + ut.expect(l_actual).not_to_be_like('%%'); + end; + + procedure create_test_case_args_package is + pragma autonomous_transaction; + begin + execute immediate q'[create or replace package test_case_args is + procedure checked(a_amount number, a_half number); + procedure ovl(a number); + procedure ovl(a varchar2, b number); + procedure ovl; + end;]'; + end; + + procedure drop_test_case_args_package is + pragma autonomous_transaction; + begin + execute immediate 'drop package test_case_args'; + end; + + procedure testcase_invalid_arguments is + l_actual clob; + l_annotations ut3_develop.ut_annotations; + begin + --Arrange + l_annotations := ut3_develop.ut_annotations( + ut3_develop.ut_annotation(1, 'suite','Cool', null), + ut3_develop.ut_annotation(14, 'test','Checked', 'checked'), + ut3_develop.ut_annotation(15, 'testcase', '[1, 2, 3]', 'checked'), + ut3_develop.ut_annotation(16, 'testcase', '{"a_x": 1}', 'checked'), + ut3_develop.ut_annotation(17, 'testcase', '{"a_half": 1}', 'checked'), + ut3_develop.ut_annotation(18, 'testcase', '{"a_amount": 1, "A_AMOUNT": 2, "a_half": 3}', 'checked'), + ut3_develop.ut_annotation(19, 'testcase', '1, 2', 'checked'), + ut3_develop.ut_annotation(20, 'testcase', 'a_amount => 1, a_half => 2', 'checked'), + ut3_develop.ut_annotation(21, 'testcase', '{"a_half": 1000, "a_amount": 2000}', 'checked') + ); + --Act + l_actual := invoke_builder_for_annotations(l_annotations, 'TEST_CASE_ARGS'); + --Assert + ut.expect(l_actual).to_be_like( + '%' || + '%has invalid arguments: 3 value(s) given, but the procedure has 2 parameter(s). Annotation ignored.' || + '%has invalid arguments: the procedure has no parameter A_X. Annotation ignored.' || + '%has invalid arguments: no value for parameter(s) A_AMOUNT. Annotation ignored.' || + '%has invalid arguments: parameter A_AMOUNT is given twice. Annotation ignored.' || + '%has invalid arguments: a JSON array or object is expected. Annotation ignored.' || + '%has invalid arguments: a JSON array or object is expected. Annotation ignored.' || + '%%' + ); + ut.expect(l_actual).to_be_like('%test_case_args.checked[7]%'); + ut.expect(l_actual).not_to_be_like('%test_case_args.checked[_]%test_case_args.checked[_]%'); + end; + + procedure testcase_json_arguments is + l_actual clob; + l_annotations ut3_develop.ut_annotations; + begin + --Arrange + l_annotations := ut3_develop.ut_annotations( + ut3_develop.ut_annotation(1, 'suite','Cool', null), + ut3_develop.ut_annotation(14, 'test','Half of {a_amount} is {a_half}', 'checked'), + ut3_develop.ut_annotation(15, 'testcase', '[2000, 1000]', 'checked'), + ut3_develop.ut_annotation(16, 'testcase', '{"a_half": 5, "a_amount": 10}', 'checked'), + ut3_develop.ut_annotation(17, 'testcase', '[1, 2, 3]', 'checked'), + ut3_develop.ut_annotation(18, 'testcase', '{"a_x": 1}', 'checked'), + ut3_develop.ut_annotation(19, 'testcase', '{"a_amount": 1}', 'checked'), + ut3_develop.ut_annotation(20, 'testcase', '[1, 2', 'checked'), + ut3_develop.ut_annotation(21, 'testcase', chr(9) || '[6, 3]', 'checked') + ); + --Act + l_actual := invoke_builder_for_annotations(l_annotations, 'TEST_CASE_ARGS'); + --Assert + ut.expect(l_actual).to_be_like( + '%checked[1]Half of 2000 is 1000%' + ); + ut.expect(l_actual).to_be_like( + '%checked[2]Half of 10 is 5%{"a_half": 5, "a_amount": 10}%' + ); + ut.expect(l_actual).to_be_like( + '%' || + '%has invalid arguments: 3 value(s) given, but the procedure has 2 parameter(s). Annotation ignored.' || + '%has invalid arguments: the procedure has no parameter A_X. Annotation ignored.' || + '%has invalid arguments: no value for parameter(s) A_HALF. Annotation ignored.' || + '%has invalid arguments: it is not valid JSON. Annotation ignored.' || + '%%' + ); + ut.expect(l_actual).not_to_be_like('%test_case_args.checked[3]%'); + ut.expect(l_actual).to_be_like('%checked[7]Half of 6 is 3%'); + end; + + procedure testcase_overloads is + l_actual clob; + l_annotations ut3_develop.ut_annotations; + begin + --Arrange + l_annotations := ut3_develop.ut_annotations( + ut3_develop.ut_annotation(1, 'suite','Cool', null), + ut3_develop.ut_annotation(14, 'test','Overloaded', 'ovl'), + ut3_develop.ut_annotation(15, 'testcase', '[5]', 'ovl'), + ut3_develop.ut_annotation(16, 'testcase', '["x", 1]', 'ovl'), + ut3_develop.ut_annotation(17, 'testcase', '[1, 2, 3]', 'ovl'), + ut3_develop.ut_annotation(18, 'testcase', '[]', 'ovl') + ); + --Act + l_actual := invoke_builder_for_annotations(l_annotations, 'TEST_CASE_ARGS'); + --Assert + ut.expect(l_actual).to_be_like( + '%test_case_args.ovl[1]%test_case_args.ovl[2]%test_case_args.ovl[4]%' + ); + ut.expect(l_actual).to_be_like( + '%%has invalid arguments: 3 value(s) given, but the procedure has 1 parameter(s). Annotation ignored.%%' + ); + ut.expect(l_actual).not_to_be_like('%test_case_args.ovl[3]%'); + end; + end test_suite_builder; / diff --git a/test/ut3_tester/core/test_suite_builder.pks b/test/ut3_tester/core/test_suite_builder.pks index 09ff3c0b3..dae8a7bcc 100644 --- a/test/ut3_tester/core/test_suite_builder.pks +++ b/test/ut3_tester/core/test_suite_builder.pks @@ -182,6 +182,44 @@ create or replace package test_suite_builder is --%endcontext + --%context(--%testcase annotation) + + --%test(Creates a separate test for each test case) + procedure testcase_creates_test_per_case; + + --%test(Replaces argument placeholders in the test description) + procedure testcase_description_placeholders; + + --%test(Gives warning when --%testcase is used without --%test) + procedure testcase_without_test; + + --%test(Stores the --%testcasesource function in the test) + procedure testcasesource_stores_query; + + --%test(Gives warning when --%testcasesource is used with --%testcase, without a function name or without --%test) + procedure testcasesource_invalid_use; + + --%endcontext + + --%context(test case argument checks) + + --%beforeall(create_test_case_args_package) + --%afterall(drop_test_case_args_package) + + --%test(Gives a warning for each test case with invalid or no JSON arguments and skips it) + procedure testcase_invalid_arguments; + + --%test(Checks JSON test case arguments and fills in the description) + procedure testcase_json_arguments; + + --%test(Accepts arguments that fit one of the overloads, including an overload without parameters) + procedure testcase_overloads; + + --%endcontext + + procedure create_test_case_args_package; + procedure drop_test_case_args_package; + --%context(--%bad_annotation) --%test(Gives warning when unknown procedure level annotation passed) diff --git a/test/ut3_tester/core/test_ut_utils.pkb b/test/ut3_tester/core/test_ut_utils.pkb index d46835f66..b74e07e84 100644 --- a/test/ut3_tester/core/test_ut_utils.pkb +++ b/test/ut3_tester/core/test_ut_utils.pkb @@ -372,6 +372,48 @@ end;'; ut.expect(anydata.convertcollection(l_list_to_be_empty)).to_be_empty; end; + procedure test_case_descr_appends is + begin + ut.expect( + ut3_develop.ut_utils.get_test_case_description( + 'A test', ut3_develop.ut_varchar2_list(null, null), ut3_develop.ut_varchar2_list('1', '2') + ) + ).to_equal('A test (1, 2)'); + end; + + procedure test_case_descr_placeholders is + begin + ut.expect( + ut3_develop.ut_utils.get_test_case_description( + 'Amount {1}, kind {a_kind}, unknown {3}', + ut3_develop.ut_varchar2_list(null, 'A_KIND'), ut3_develop.ut_varchar2_list('100', q'['VIP']') + ) + ).to_equal(q'[Amount 100, kind 'VIP', unknown {3}]'); + end; + + procedure test_case_descr_shortens is + begin + ut.expect( + ut3_develop.ut_utils.get_test_case_description( + 'Long {1}', ut3_develop.ut_varchar2_list(null), ut3_develop.ut_varchar2_list(rpad('x', 101, 'x')) + ) + ).to_equal('Long ' || rpad('x', 100, 'x') || '...'); + ut.expect( + ut3_develop.ut_utils.get_test_case_description( + 'Long', ut3_develop.ut_varchar2_list(null, null), ut3_develop.ut_varchar2_list(rpad('x', 100, 'x'), 'y') + ) + ).to_equal('Long (' || rpad('x', 100, 'x') || ', y)'); + end; + + procedure test_case_descr_null is + begin + ut.expect( + ut3_develop.ut_utils.get_test_case_description( + null, ut3_develop.ut_varchar2_list(null), ut3_develop.ut_varchar2_list('1') + ) + ).to_be_null(); + end; + procedure replace_multiline_comments is l_source clob; diff --git a/test/ut3_tester/core/test_ut_utils.pks b/test/ut3_tester/core/test_ut_utils.pks index 82145f908..c9abe0f6a 100644 --- a/test/ut3_tester/core/test_ut_utils.pks +++ b/test/ut3_tester/core/test_ut_utils.pks @@ -124,6 +124,22 @@ create or replace package test_ut_utils is --%endcontext + --%context(get_test_case_description) + + --%test(Appends the arguments when the description has no placeholders) + procedure test_case_descr_appends; + + --%test(Replaces placeholders by position and by name) + procedure test_case_descr_placeholders; + + --%test(Shortens values longer than 100 characters and appends the values when no appendix is given) + procedure test_case_descr_shortens; + + --%test(Keeps a null description null) + procedure test_case_descr_null; + + --%endcontext + --%test(replace_multiline_comments - replaces multi-line comments with empty lines) procedure replace_multiline_comments; diff --git a/test/ut3_user/api/test_ut_test_cases.pkb b/test/ut3_user/api/test_ut_test_cases.pkb new file mode 100644 index 000000000..278d3b4c5 --- /dev/null +++ b/test/ut3_user/api/test_ut_test_cases.pkb @@ -0,0 +1,1494 @@ +create or replace package body test_ut_test_cases is + + g_time_zone varchar2(100); + g_nls_parameters ut3_develop.ut_key_value_pairs; + + c_discount_cases constant varchar2(4000) := + 'Discount for REGULAR customer with order total 500 on 2026-03-15T14:30:00 is 0.05' || chr(10) || + 'Discount for REGULAR customer with order total 1000 on 2026-04-01T09:00:00 is 0.1' || chr(10) || + 'Discount for VIP customer with order total 50 on 2026-03-20T10:00:00 is 0.25' || chr(10) || + 'Discount for REGULAR customer with order total null on 2026-02-28T23:59:59 is 0'; + + -- the spec and body of a suite with the example of discussion #1326; a_annotations, a_spec and a_body make the variants + procedure create_discount_suite(a_name varchar2, a_annotations varchar2, a_spec varchar2 := null, a_body varchar2 := null) is + begin + execute immediate replace(replace(replace(q'~create or replace package as + + --%suite(Discount calculation) + + --%test(Discount for {a_customer_type} customer with order total {a_order_total} on {a_order_date} is {a_expected}) + + procedure discount_by_customer_type( + a_order_total number, + a_customer_type varchar2, + a_order_date date, + a_promo_start timestamp, + a_promo_end timestamp with time zone, + a_expected number + ); + +end;~', '', a_name), '', a_annotations), '', a_spec); + execute immediate replace(replace(q'~create or replace package body as + + procedure discount_by_customer_type( + a_order_total number, + a_customer_type varchar2, + a_order_date date, + a_promo_start timestamp, + a_promo_end timestamp with time zone, + a_expected number + ) is + begin + ut3_develop.ut.expect( + get_discount(a_order_total, a_customer_type, a_order_date, a_promo_start, a_promo_end) + ).to_equal( a_expected ); + end; + +end;~', '', a_name), '', a_body); + end; + + procedure create_test_case_suites is + pragma autonomous_transaction; + l_boolean_spec varchar2(4000); + l_boolean_body varchar2(4000); + l_wide_parameters varchar2(4000); + begin + execute immediate 'create or replace type test_case_pair force as object (amount number, half number)'; + execute immediate 'create or replace type test_case_numbers force as table of number'; + execute immediate 'create table test_case_rows (a_amount number, a_half number)'; + + execute immediate q'~create or replace function get_discount( + a_order_total number, + a_customer_type varchar2, + a_order_date date, + a_promo_start timestamp, + a_promo_end timestamp with time zone +) return number is + l_discount number; +begin + if a_customer_type = 'VIP' then + l_discount := 0.2; + elsif a_customer_type = 'REGULAR' then + l_discount := case when a_order_total >= 1000 then 0.1 else 0 end; + else + raise_application_error(-20001, 'Unknown customer type: ' || a_customer_type); + end if; + if a_order_date >= a_promo_start and a_order_date < a_promo_end then + l_discount := l_discount + 0.05; + end if; + return l_discount; +end;~'; + + create_discount_suite( + 'tc_discount_json', + q'~ --%testcase([500, "REGULAR", "2026-03-15T14:30:00", "2026-03-01T00:00:00.000000", "2026-03-31T23:59:59.999999+02:00", 0.05]) + --%testcase([1000, "REGULAR", "2026-04-01T09:00:00", "2026-03-01T00:00:00.000000", "2026-03-31T23:59:59.999999+02:00", 0.1]) + --%testcase({"a_order_total": 50, "a_customer_type": "VIP", "a_order_date": "2026-03-20T10:00:00", "a_promo_start": "2026-03-01T00:00:00.000000", "a_promo_end": "2026-03-31T23:59:59.999999-05:00", "a_expected": 0.25}) + --%testcase({"a_order_total": null, "a_customer_type": "REGULAR", "a_order_date": "2026-02-28T23:59:59", "a_promo_start": "2026-03-01T00:00:00.000000", "a_promo_end": "2026-03-31T23:59:59.999999+02:00", "a_expected": 0})~' + ); + create_discount_suite( + 'tc_discount_source', + ' --%testcasesource(discount_cases)', + ' function discount_cases return json_array_t;', + q'~ + function discount_cases return json_array_t is + begin + return json_array_t(q'[ + [ + [500, "REGULAR", "2026-03-15T14:30:00", "2026-03-01T00:00:00.000000", "2026-03-31T23:59:59.999999+02:00", 0.05], + [1000, "REGULAR", "2026-04-01T09:00:00", "2026-03-01T00:00:00.000000", "2026-03-31T23:59:59.999999+02:00", 0.1], + { + "a_order_total": 50, + "a_customer_type": "VIP", + "a_order_date": "2026-03-20T10:00:00", + "a_promo_start": "2026-03-01T00:00:00.000000", + "a_promo_end": "2026-03-31T23:59:59.999999-05:00", + "a_expected": 0.25 + }, + { + "a_order_total": null, + "a_customer_type": "REGULAR", + "a_order_date": "2026-02-28T23:59:59", + "a_promo_start": "2026-03-01T00:00:00.000000", + "a_promo_end": "2026-03-31T23:59:59.999999+02:00", + "a_expected": 0 + } + ] + ]'); + end;~' + ); + create_discount_suite( + 'tc_discount_cursor', + ' --%testcasesource(discount_cases)', + ' function discount_cases return sys_refcursor;', + q'~ + function discount_cases return sys_refcursor is + l_cursor sys_refcursor; + begin + open l_cursor for + select 500 as a_order_total, + 'REGULAR' as a_customer_type, + to_date('2026-03-15 14:30:00', 'yyyy-mm-dd hh24:mi:ss') as a_order_date, + to_timestamp('2026-03-01 00:00:00.000000', 'yyyy-mm-dd hh24:mi:ss.ff') as a_promo_start, + to_timestamp_tz('2026-03-31 23:59:59.999999 +02:00', 'yyyy-mm-dd hh24:mi:ss.ff tzh:tzm') as a_promo_end, + 0.05 as a_expected + from dual + union all + select 1000, 'REGULAR', + to_date('2026-04-01 09:00:00', 'yyyy-mm-dd hh24:mi:ss'), + to_timestamp('2026-03-01 00:00:00.000000', 'yyyy-mm-dd hh24:mi:ss.ff'), + to_timestamp_tz('2026-03-31 23:59:59.999999 +02:00', 'yyyy-mm-dd hh24:mi:ss.ff tzh:tzm'), + 0.1 + from dual + union all + select 50, 'VIP', + to_date('2026-03-20 10:00:00', 'yyyy-mm-dd hh24:mi:ss'), + to_timestamp('2026-03-01 00:00:00.000000', 'yyyy-mm-dd hh24:mi:ss.ff'), + to_timestamp_tz('2026-03-31 23:59:59.999999 -05:00', 'yyyy-mm-dd hh24:mi:ss.ff tzh:tzm'), + 0.25 + from dual + union all + select null, 'REGULAR', + to_date('2026-02-28 23:59:59', 'yyyy-mm-dd hh24:mi:ss'), + to_timestamp('2026-03-01 00:00:00.000000', 'yyyy-mm-dd hh24:mi:ss.ff'), + to_timestamp_tz('2026-03-31 23:59:59.999999 +02:00', 'yyyy-mm-dd hh24:mi:ss.ff tzh:tzm'), + 0 + from dual; + return l_cursor; + end;~' + ); + + execute immediate q'~create or replace package tc_inline as + --%suite(Inline test cases) + + --%test(Half of {a_amount} is {a_half}) + --%testcase([2000, 1000]) + --%testcase({"a_half": 5, "a_amount": 10}) + --%testcase([3, 2]) + --%testcase({"A_AMOUNT": 8, "a_half": 4}) + --%testcase([1, 1]) + procedure half(a_amount number, a_half number); + + --%test(Text {1}) + --%testcase({"a_text": "it's \"quoted\"", "a_case": 1}) + --%testcase(["it's \"quoted\"", 2]) + --%testcase(["~' || unistr('\00e4\00f6\00fc\20ac') || q'~", 3]) + --%testcase(["\u00e4\u00f6\u00fc\u20ac", 4]) + procedure strings(a_text varchar2, a_case number); + + --%test(Default for {a_required}) + --%testcase({"a_required": 1}) + --%testcase({"A_REQUIRED": 2}) + --%testcase([3]) + procedure defaults(a_required number, a_optional varchar2 := 'default'); + + --%test(Conversions) + --%testcase(["0.05", 5]) + procedure conversions(a_number number, a_text varchar2); + + --%test(Flag {a_flag} is {a_label}) + --%testcase([true, "yes"]) + --%testcase({"a_flag": false, "a_label": "no"}) + --%testcase([null, "null"]) + --%testcase(["yes", "error"]) + procedure booleans(a_flag boolean, a_label varchar2); + + --%test(Objects) + --%testcase([{"amount": 8, "half": 4}, [1, 2, 3]]) + --%testcase([{"AMOUNT": 6, "HALF": 3}, [1]]) + --%testcase([null, null]) + --%testcase([{"amount": 8}, [1]]) + --%testcase([{"amount": 8, "halfx": 4}, [1]]) + --%testcase([{"amount": 8, "half": 4}, 5]) + procedure objects(a_pair test_case_pair, a_numbers test_case_numbers); + + --%test(Unsupported type) + --%testcase([""]) + procedure unsupported(a_xml xmltype); + + --%test(Overloaded) + --%testcase([1]) + procedure overloaded(a number); + procedure overloaded(a varchar2, b number); + + --%test(Arguments that don't fit) + --%testcase([{"amount": 1, "half": 1}]) + --%testcase([1]) + --%testcase([{"amount": "x", "half": 1}]) + procedure arguments_dont_fit(a_pair test_case_pair); + + --%test(Not JSON) + --%testcase(1, 2) + --%testcase([1, 2]) + procedure not_json(a_first number, a_second number); + + --%test(More types) + --%testcase([1.5, "n\u00e4", "P1DT2H", "P1Y2M", "0AFF", "long text"]) + procedure more_types(a_double binary_double, a_national nvarchar2, a_ds interval day to second, a_ym interval year to month, a_raw raw, a_clob clob); + + --%test(No parameters) + --%testcase([]) + --%testcase({}) + procedure no_parameters; + + type t_record is record (a number); + type t_numbers is table of number; + + --%test(Record parameter) + --%testcase([{"a": 1}]) + procedure record_parameter(a_record t_record); + + --%test(Package collection parameter) + --%testcase([[1, 2]]) + procedure package_collection_parameter(a_numbers t_numbers); + + --%test(JSON object parameter) + --%testcase([{"a": 1}]) + procedure json_object_parameter(a_object json_object_t); + + --%test(BLOB parameter) + --%testcase(["0AFF"]) + procedure blob_parameter(a_blob blob); +end;~'; + execute immediate q'~create or replace package body tc_inline as + procedure half(a_amount number, a_half number) is + begin + ut3_develop.ut.expect(a_amount / 2).to_equal(a_half); + end; + procedure strings(a_text varchar2, a_case number) is + begin + ut3_develop.ut.expect(a_text).to_equal(case when a_case <= 2 then 'it''s "quoted"' else unistr('\00e4\00f6\00fc\20ac') end); + end; + procedure defaults(a_required number, a_optional varchar2 := 'default') is + begin + ut3_develop.ut.expect(a_required).to_be_not_null(); + ut3_develop.ut.expect(a_optional).to_equal('default'); + end; + procedure conversions(a_number number, a_text varchar2) is + begin + ut3_develop.ut.expect(a_number).to_equal(0.05); + ut3_develop.ut.expect(a_text).to_equal('5'); + end; + procedure booleans(a_flag boolean, a_label varchar2) is + begin + ut3_develop.ut.expect(case when a_flag then 'yes' when not a_flag then 'no' else 'null' end).to_equal(a_label); + end; + procedure objects(a_pair test_case_pair, a_numbers test_case_numbers) is + begin + if a_pair is null then + ut3_develop.ut.expect(a_numbers is null).to_be_true(); + else + ut3_develop.ut.expect(a_pair.amount / 2).to_equal(a_pair.half); + ut3_develop.ut.expect(a_numbers.count).to_equal(a_pair.amount - 5); + end if; + end; + procedure unsupported(a_xml xmltype) is + begin + null; + end; + procedure not_json(a_first number, a_second number) is + begin + ut3_develop.ut.expect(a_second).to_equal(2); + end; + procedure overloaded(a number) is + begin + null; + end; + procedure overloaded(a varchar2, b number) is + begin + null; + end; + procedure arguments_dont_fit(a_pair test_case_pair) is + begin + ut3_develop.ut.expect(a_pair.amount).to_equal(1); + end; + procedure more_types(a_double binary_double, a_national nvarchar2, a_ds interval day to second, a_ym interval year to month, a_raw raw, a_clob clob) is + begin + ut3_develop.ut.expect(a_double).to_equal(1.5d); + ut3_develop.ut.expect(a_national = unistr('n\00e4')).to_be_true(); + ut3_develop.ut.expect(a_ds).to_equal(interval '1 02:00:00' day to second); + ut3_develop.ut.expect(a_ym).to_equal(interval '1-2' year to month); + ut3_develop.ut.expect(rawtohex(a_raw)).to_equal('0AFF'); + ut3_develop.ut.expect(a_clob).to_equal(to_clob('long text')); + end; + procedure no_parameters is + begin + null; + end; + procedure record_parameter(a_record t_record) is + begin + null; + end; + procedure package_collection_parameter(a_numbers t_numbers) is + begin + null; + end; + procedure json_object_parameter(a_object json_object_t) is + begin + null; + end; + procedure blob_parameter(a_blob blob) is + begin + null; + end; +end;~'; + + execute immediate q'~create or replace package tc_sources as + function get_cases return json_array_t; +end;~'; + execute immediate q'~create or replace package body tc_sources as + function get_cases return json_array_t is + begin + return json_array_t('[[4, 2], {"a_half": 5, "a_amount": 10}]'); + end; +end;~'; + + execute immediate q'~create or replace package tc_json_source as + --%suite(JSON sources) + --%beforeall(fill_rows) + + c_limit constant number := 100; + procedure fill_rows; + + --%test(Half of {a_amount} from table is {a_half}) + --%testcasesource(get_rows) + procedure from_table(a_amount number, a_half number); + function get_rows return json_array_t; + + --%test(From another package: half of {a_amount} is {a_half}) + --%testcasesource(tc_sources.get_cases) + procedure from_other_package(a_amount number, a_half number); + + --%test(From owner and package: half of {a_amount} is {a_half}) + --%testcasesource(ut3_user.tc_sources.get_cases) + procedure from_owner_and_package(a_amount number, a_half number); + + --%test(From a function with default arguments: half of {a_amount} is {a_half}) + --%testcasesource(get_with_default) + procedure from_function_with_default(a_amount number, a_half number); + function get_with_default(a_factor number := 2) return json_array_t; + + --%test(Built with the PL/SQL JSON API) + --%testcasesource(get_built) + procedure built(a_day date, a_limit number, a_moment timestamp with time zone); + function get_built return json_array_t; + + --%test(Empty array) + --%testcasesource(get_empty) + procedure empty_array(a_value number); + function get_empty return json_array_t; + + --%test(Null) + --%testcasesource(get_null) + procedure null_result(a_value number); + function get_null return json_array_t; + + --%test(json_arrayagg over no rows) + --%testcasesource(get_no_rows) + procedure no_rows(a_value number); + function get_no_rows return json_array_t; + + --%test(Object instead of array) + --%testcasesource(get_object) + procedure not_an_array(a_value number); + function get_object return json_array_t; + + --%test(Scalar element) + --%testcasesource(get_scalar) + procedure scalar_element(a_value number); + function get_scalar return json_array_t; + + --%test(Invalid JSON) + --%testcasesource(get_invalid) + procedure invalid_json(a_value number); + function get_invalid return json_array_t; + + --%test(Wrong return type) + --%testcasesource(get_number) + procedure wrong_return_type(a_value number); + function get_number return number; + + --%test(JSON as text) + --%testcasesource(get_clob) + procedure json_as_text(a_value number); + function get_clob return clob; + + --%test(Missing function) + --%testcasesource(get_nothing) + procedure missing_function(a_value number); + + --%test(Failing function) + --%testcasesource(get_failing) + procedure failing_function(a_value number); + function get_failing return json_array_t; + + --%test(Disabled) + --%disabled + --%testcasesource(get_failing) + procedure disabled_source(a_value number); + + --%test(Values that don't fit) + --%testcasesource(get_mismatching) + procedure mismatching(a_number number, a_text varchar2); + function get_mismatching return json_array_t; + + --%test(Long values) + --%testcasesource(get_long) + procedure long_values(a_text varchar2, a_note clob); + function get_long return json_array_t; + + --%test + --%testcasesource(get_one) + procedure no_description(a_value number); + function get_one return json_array_t; + + --%test(Overloaded) + --%testcasesource(get_one) + procedure overloaded(a_value number); + procedure overloaded(a_value varchar2, a_other number); +end;~'; + execute immediate q'~create or replace package body tc_json_source as + procedure fill_rows is + begin + insert into test_case_rows values (10, 5); + insert into test_case_rows values (3, 2); + insert into test_case_rows values (4, 2); + end; + procedure check_half(a_amount number, a_half number) is + begin + ut3_develop.ut.expect(a_amount / 2).to_equal(a_half); + end; + procedure from_table(a_amount number, a_half number) is + begin + check_half(a_amount, a_half); + end; + function get_rows return json_array_t is + l_json clob; + begin + select json_arrayagg(json_object('a_amount' value a_amount, 'a_half' value a_half) order by a_amount returning clob) + into l_json + from test_case_rows; + return json_array_t(nvl(l_json, '[]')); + end; + procedure from_other_package(a_amount number, a_half number) is + begin + check_half(a_amount, a_half); + end; + procedure from_owner_and_package(a_amount number, a_half number) is + begin + check_half(a_amount, a_half); + end; + procedure from_function_with_default(a_amount number, a_half number) is + begin + check_half(a_amount, a_half); + end; + function get_with_default(a_factor number := 2) return json_array_t is + begin + return json_array_t('[[' || 3 * a_factor || ', 3]]'); + end; + procedure built(a_day date, a_limit number, a_moment timestamp with time zone) is + begin + ut3_develop.ut.expect(a_day).to_equal(trunc(sysdate)); + ut3_develop.ut.expect(a_limit).to_equal(c_limit); + ut3_develop.ut.expect(a_moment).to_be_between(systimestamp - interval '1' minute, systimestamp); + end; + function get_built return json_array_t is + l_cases json_array_t := json_array_t(); + l_case json_object_t := json_object_t(); + begin + l_case.put('a_day', trunc(sysdate)); + l_case.put('a_limit', c_limit); + -- Oracle 19c has no put for TIMESTAMP WITH TIME ZONE; localtimestamp is a TIMESTAMP in the session time zone + l_case.put('a_moment', localtimestamp); + l_cases.append(l_case); + return l_cases; + end; + procedure empty_array(a_value number) is + begin + null; + end; + function get_empty return json_array_t is + begin + return json_array_t(); + end; + procedure null_result(a_value number) is + begin + null; + end; + function get_null return json_array_t is + begin + return null; + end; + procedure no_rows(a_value number) is + begin + null; + end; + function get_no_rows return json_array_t is + l_json clob; + begin + select json_arrayagg(json_array(a_amount) returning clob) into l_json from test_case_rows where 1 = 0; + -- json_arrayagg returns null when there are no rows, and json_array_t can't parse null + return json_array_t(nvl(l_json, '[]')); + end; + procedure not_an_array(a_value number) is + begin + null; + end; + function get_object return json_array_t is + begin + return json_array_t('{"a_value": 1}'); + end; + procedure scalar_element(a_value number) is + begin + null; + end; + function get_scalar return json_array_t is + begin + return json_array_t('[[1], 2]'); + end; + procedure invalid_json(a_value number) is + begin + null; + end; + function get_invalid return json_array_t is + begin + return json_array_t('[[1],'); + end; + procedure wrong_return_type(a_value number) is + begin + null; + end; + function get_number return number is + begin + return 1; + end; + procedure json_as_text(a_value number) is + begin + null; + end; + function get_clob return clob is + begin + return '[[1]]'; + end; + procedure missing_function(a_value number) is + begin + null; + end; + procedure failing_function(a_value number) is + begin + null; + end; + function get_failing return json_array_t is + begin + raise_application_error(-20999, 'Test case source failed on purpose'); + end; + procedure disabled_source(a_value number) is + begin + null; + end; + procedure mismatching(a_number number, a_text varchar2) is + begin + ut3_develop.ut.expect(a_number).to_equal(1); + end; + function get_mismatching return json_array_t is + begin + return json_array_t('[[1, "x"], ["abc", "x"], [1, "x", 3, 4], {"a_x": 1}, {"a_number": 1, "A_NUMBER": 1}, [1, {"a": 1}], {"a_text": "x"}]'); + end; + procedure long_values(a_text varchar2, a_note clob) is + begin + ut3_develop.ut.expect(length(a_text)).to_equal(5000); + ut3_develop.ut.expect(dbms_lob.getlength(a_note)).to_equal(100000); + end; + function get_long return json_array_t is + l_note clob; + begin + for i in 1 .. 10 loop + l_note := l_note || rpad('x', 10000, 'x'); + end loop; + -- parsed as JSON text: Oracle 19c has no append for CLOB, and json_element_t.parse rejects a scalar + return json_array_t('[["' || rpad('y', 5000, 'y') || '", "' || l_note || '"]]'); + end; + procedure no_description(a_value number) is + begin + null; + end; + function get_one return json_array_t is + begin + return json_array_t('[[1]]'); + end; + procedure overloaded(a_value number) is + begin + null; + end; + procedure overloaded(a_value varchar2, a_other number) is + begin + null; + end; +end;~'; + + $if dbms_db_version.version >= 23 $then + l_boolean_spec := q'~ + --%test(Flag {a_flag} is {a_label}) + --%testcasesource(get_booleans) + procedure booleans(a_flag boolean, a_label varchar2); + function get_booleans return sys_refcursor;~'; + l_boolean_body := q'~ + procedure booleans(a_flag boolean, a_label varchar2) is + begin + ut3_develop.ut.expect(case when a_flag then 'yes' when not a_flag then 'no' else 'null' end).to_equal(a_label); + end; + function get_booleans return sys_refcursor is + l_cursor sys_refcursor; + begin + open l_cursor for + select true a_flag, 'yes' a_label from dual union all + select false, 'no' from dual union all + select cast(null as boolean), 'null' from dual; + return l_cursor; + end;~'; + $end + -- named arguments for 200 parameters are longer than the arguments of a test can be + for i in 1 .. 200 loop + l_wide_parameters := l_wide_parameters || case when i > 1 then ', ' end || 'c' || i || ' number'; + end loop; + execute immediate replace(q'~create or replace package tc_cursor_source as + --%suite(Cursor sources) + --%beforeall(fill_rows) + + c_limit constant number := 100; + procedure fill_rows; + procedure delete_rows; + + --%test(Cursor case {label} with limit {a_limit}) + --%testcasesource(get_by_name) + procedure by_name(a_day date, a_limit number, a_pair test_case_pair); + function get_by_name return sys_refcursor; + + --%test(Position: half of {1} is {2}) + --%testcasesource(get_by_position) + procedure by_position(a_amount number, a_half number); + function get_by_position return sys_refcursor; + + --%test(Snapshot: half of {a_amount} is {a_half}) + --%testcasesource(get_rows) + --%beforetest(delete_rows) + procedure snapshot(a_amount number, a_half number); + function get_rows return sys_refcursor; + + --%test(No rows) + --%testcasesource(get_no_rows) + procedure no_rows(a_value number); + function get_no_rows return sys_refcursor; + + --%test(Unsupported column) + --%testcasesource(get_xml) + procedure unsupported_column(a_xml clob); + function get_xml return sys_refcursor; + + --%test(Column that doesn't fit) + --%testcasesource(get_wrong_column) + procedure column_doesnt_fit(a_pair test_case_pair); + function get_wrong_column return sys_refcursor; + + --%test(Many rows) + --%testcasesource(get_many) + procedure many_rows(a_value number); + function get_many return sys_refcursor; + + --%test(Cursor types) + --%testcasesource(get_types) + procedure types( + a_char char, a_nchar nchar, a_nvarchar nvarchar2, a_float binary_float, a_double binary_double, + a_ltz timestamp with local time zone, a_ds interval day to second, a_ym interval year to month, + a_clob clob, a_nclob nclob, a_blob blob, a_raw raw, a_numbers test_case_numbers + ); + function get_types return sys_refcursor; + + --%test(Too many columns) + --%testcasesource(get_wide) + procedure too_many_columns(); + function get_wide return sys_refcursor; + + --%test(Position count) + --%testcasesource(get_three) + procedure position_count(a_amount number, a_half number); + function get_three return sys_refcursor; + + --%test(Misspelled column) + --%testcasesource(get_misspelled) + procedure misspelled_column(a_amount number, a_half number := 0); + function get_misspelled return sys_refcursor; + + --%test(Missing column) + --%testcasesource(get_amount) + procedure missing_column(a_amount number, a_half number); + function get_amount return sys_refcursor; + + --%test(Duplicate column) + --%testcasesource(get_duplicate) + procedure duplicate_column(a_amount number); + function get_duplicate return sys_refcursor; + + --%test(Lower case {a_amount}) + --%testcasesource(get_lower_case) + procedure lower_case_column(a_amount number, a_half number := 2); + function get_lower_case return sys_refcursor; + + --%test(Overloaded) + --%testcasesource(get_amount) + procedure overloaded(a_amount number); + procedure overloaded(a_amount varchar2, a_other number); +~' || l_boolean_spec || q'~ +end;~', '', l_wide_parameters); + execute immediate replace(q'~create or replace package body tc_cursor_source as + procedure fill_rows is + begin + insert into test_case_rows values (10, 5); + insert into test_case_rows values (3, 2); + insert into test_case_rows values (4, 2); + end; + procedure delete_rows is + begin + delete from test_case_rows; + end; + procedure by_name(a_day date, a_limit number, a_pair test_case_pair) is + begin + ut3_develop.ut.expect(a_day).to_be_between(trunc(sysdate), trunc(sysdate) + 1); + ut3_develop.ut.expect(a_limit).to_be_greater_or_equal(c_limit); + ut3_develop.ut.expect(a_pair.amount / 2).to_equal(a_pair.half); + end; + function get_by_name return sys_refcursor is + l_cursor sys_refcursor; + begin + open l_cursor for + select 'today' label, trunc(sysdate) a_day, c_limit a_limit, test_case_pair(8, 4) a_pair from dual + union all + select 'tomorrow', trunc(sysdate) + 1, c_limit * 2, test_case_pair(6, 3) from dual + order by 1; + return l_cursor; + end; + procedure by_position(a_amount number, a_half number) is + begin + ut3_develop.ut.expect(a_amount / 2).to_equal(a_half); + end; + function get_by_position return sys_refcursor is + l_cursor sys_refcursor; + begin + open l_cursor for select 4 x, 2 y from dual union all select 10, 5 from dual; + return l_cursor; + end; + procedure snapshot(a_amount number, a_half number) is + begin + ut3_develop.ut.expect(a_amount).to_be_not_null(); + ut3_develop.ut.expect(a_half).to_be_not_null(); + end; + function get_rows return sys_refcursor is + l_cursor sys_refcursor; + begin + open l_cursor for select a_amount, a_half from test_case_rows order by a_amount; + return l_cursor; + end; + procedure no_rows(a_value number) is + begin + null; + end; + function get_no_rows return sys_refcursor is + l_cursor sys_refcursor; + begin + open l_cursor for select 1 a_value from dual where 1 = 0; + return l_cursor; + end; + procedure unsupported_column(a_xml clob) is + begin + null; + end; + function get_xml return sys_refcursor is + l_cursor sys_refcursor; + begin + open l_cursor for select xmltype('') a_xml from dual; + return l_cursor; + end; + procedure column_doesnt_fit(a_pair test_case_pair) is + begin + null; + end; + function get_wrong_column return sys_refcursor is + l_cursor sys_refcursor; + begin + open l_cursor for select 1 a_pair from dual; + return l_cursor; + end; + procedure many_rows(a_value number) is + begin + ut3_develop.ut.expect(a_value).to_be_between(1, 300); + end; + function get_many return sys_refcursor is + l_cursor sys_refcursor; + begin + open l_cursor for select level a_value from dual connect by level <= 300; + return l_cursor; + end; + procedure types( + a_char char, a_nchar nchar, a_nvarchar nvarchar2, a_float binary_float, a_double binary_double, + a_ltz timestamp with local time zone, a_ds interval day to second, a_ym interval year to month, + a_clob clob, a_nclob nclob, a_blob blob, a_raw raw, a_numbers test_case_numbers + ) is + begin + ut3_develop.ut.expect(a_char).to_equal('a '); + ut3_develop.ut.expect(a_nchar = n'b ').to_be_true(); + ut3_develop.ut.expect(a_nvarchar = n'c').to_be_true(); + ut3_develop.ut.expect(a_float = 1.5f).to_be_true(); + ut3_develop.ut.expect(a_double = 2.5d).to_be_true(); + ut3_develop.ut.expect(cast(a_ltz as timestamp)).to_equal(timestamp '2026-03-31 12:00:00'); + ut3_develop.ut.expect(a_ds).to_equal(interval '1 02:00:00' day to second); + ut3_develop.ut.expect(a_ym).to_equal(interval '1-2' year to month); + ut3_develop.ut.expect(a_clob).to_equal(to_clob('long')); + ut3_develop.ut.expect(to_clob(a_nclob)).to_equal(to_clob('nlong')); + ut3_develop.ut.expect(a_blob).to_equal(to_blob(hextoraw('0AFF'))); + ut3_develop.ut.expect(rawtohex(a_raw)).to_equal('0BEE'); + ut3_develop.ut.expect(a_numbers.count).to_equal(2); + end; + function get_types return sys_refcursor is + l_cursor sys_refcursor; + begin + open l_cursor for + select cast('a' as char(3)) a_char, cast(n'b' as nchar(2)) a_nchar, cast(n'c' as nvarchar2(10)) a_nvarchar, + cast(1.5 as binary_float) a_float, cast(2.5 as binary_double) a_double, + cast(timestamp '2026-03-31 12:00:00' as timestamp with local time zone) a_ltz, + interval '1 02:00:00' day to second a_ds, interval '1-2' year to month a_ym, + to_clob('long') a_clob, to_nclob('nlong') a_nclob, to_blob(hextoraw('0AFF')) a_blob, hextoraw('0BEE') a_raw, + test_case_numbers(1, 2) a_numbers + from dual; + return l_cursor; + end; + procedure too_many_columns() is + begin + null; + end; + function get_wide return sys_refcursor is + l_cursor sys_refcursor; + l_select varchar2(32767); + begin + for i in 1 .. 200 loop + l_select := l_select || case when i > 1 then ', ' end || i || ' c' || i; + end loop; + open l_cursor for 'select ' || l_select || ' from dual'; + return l_cursor; + end; + procedure position_count(a_amount number, a_half number) is + begin + null; + end; + function get_three return sys_refcursor is + l_cursor sys_refcursor; + begin + open l_cursor for select 4 x, 2 y, 0 z from dual; + return l_cursor; + end; + procedure misspelled_column(a_amount number, a_half number := 0) is + begin + null; + end; + function get_misspelled return sys_refcursor is + l_cursor sys_refcursor; + begin + open l_cursor for select 4 a_amount, 2 a_halv from dual; + return l_cursor; + end; + procedure missing_column(a_amount number, a_half number) is + begin + null; + end; + function get_amount return sys_refcursor is + l_cursor sys_refcursor; + begin + open l_cursor for select 4 a_amount from dual; + return l_cursor; + end; + procedure duplicate_column(a_amount number) is + begin + null; + end; + function get_duplicate return sys_refcursor is + l_cursor sys_refcursor; + begin + open l_cursor for select 4 a_amount, 5 "a_amount" from dual; + return l_cursor; + end; + procedure lower_case_column(a_amount number, a_half number := 2) is + begin + ut3_develop.ut.expect(a_amount / 2).to_equal(a_half); + end; + function get_lower_case return sys_refcursor is + l_cursor sys_refcursor; + begin + open l_cursor for select 4 "a_amount" from dual; + return l_cursor; + end; + procedure overloaded(a_amount number) is + begin + null; + end; + procedure overloaded(a_amount varchar2, a_other number) is + begin + null; + end; +~' || l_boolean_body || q'~ +end;~', '', l_wide_parameters); + + execute immediate q'~create or replace package tc_times as + --%suite(Dates and times) + + --%test(JSON {1}) + --%testcase(["2026-03-31T12:00:00-05:00", "2026-03-31T12:00:00.123456", "2026-03-31T12:00:00", "2026-03-31T12:00:00Z"]) + --%testcase({"a_date": "2026-03-31T12:00:00 -05:00", "a_ts": "2026-03-31T12:00:00.123456", "a_tz": "2026-03-31T12:00:00", "a_ltz": "2026-03-31T12:00:00Z"}) + procedure json_strings(a_date date, a_ts timestamp, a_tz timestamp with time zone, a_ltz timestamp with local time zone); + + --%test(Cursor) + --%testcasesource(get_times) + procedure cursor_values(a_date date, a_ts timestamp, a_tz timestamp with time zone, a_ltz timestamp with local time zone); + function get_times return sys_refcursor; + + --%test(Date only {1}) + --%testcase(["2026-03-15", "2026-03-15"]) + procedure date_only(a_date date, a_ts timestamp); + + --%test(Other format {1}) + --%testcase(["31.03.2026"]) + procedure other_format(a_date date); +end;~'; + execute immediate q'~create or replace package body tc_times as + procedure check_values(a_date date, a_ts timestamp, a_tz timestamp with time zone, a_ltz timestamp with local time zone) is + begin + -- a time zone is dropped when the value is assigned to a DATE or TIMESTAMP, as in any PL/SQL assignment + ut3_develop.ut.expect(to_char(a_date, 'yyyy-mm-dd hh24:mi:ss')).to_equal('2026-03-31 12:00:00'); + ut3_develop.ut.expect(to_char(a_ts, 'yyyy-mm-dd hh24:mi:ss.ff6')).to_equal('2026-03-31 12:00:00.123456'); + -- a value without time zone gets the session time zone; its offset on that date, not today (daylight saving time) + ut3_develop.ut.expect(to_char(a_tz, 'yyyy-mm-dd hh24:mi:ss tzh:tzm')).to_equal( + to_char(from_tz(timestamp '2026-03-31 12:00:00', sessiontimezone), 'yyyy-mm-dd hh24:mi:ss tzh:tzm') + ); + ut3_develop.ut.expect(to_char(a_ltz, 'yyyy-mm-dd hh24:mi:ss')).to_equal( + to_char(from_tz(timestamp '2026-03-31 12:00:00', '+00:00') at time zone sessiontimezone, 'yyyy-mm-dd hh24:mi:ss') + ); + end; + procedure json_strings(a_date date, a_ts timestamp, a_tz timestamp with time zone, a_ltz timestamp with local time zone) is + begin + check_values(a_date, a_ts, a_tz, a_ltz); + end; + procedure cursor_values(a_date date, a_ts timestamp, a_tz timestamp with time zone, a_ltz timestamp with local time zone) is + begin + check_values(a_date, a_ts, a_tz, a_ltz); + end; + function get_times return sys_refcursor is + l_cursor sys_refcursor; + begin + open l_cursor for + select to_timestamp_tz('2026-03-31 12:00:00 -05:00', 'yyyy-mm-dd hh24:mi:ss tzh:tzm') a_date, + to_timestamp('2026-03-31 12:00:00.123456', 'yyyy-mm-dd hh24:mi:ss.ff6') a_ts, + cast(timestamp '2026-03-31 12:00:00' as timestamp with time zone) a_tz, + to_timestamp_tz('2026-03-31 12:00:00 +00:00', 'yyyy-mm-dd hh24:mi:ss tzh:tzm') a_ltz + from dual; + return l_cursor; + end; + procedure date_only(a_date date, a_ts timestamp) is + begin + ut3_develop.ut.expect(to_char(a_date, 'yyyy-mm-dd hh24:mi:ss')).to_equal('2026-03-15 00:00:00'); + ut3_develop.ut.expect(to_char(a_ts, 'yyyy-mm-dd hh24:mi:ss.ff3')).to_equal('2026-03-15 00:00:00.000'); + end; + procedure other_format(a_date date) is + begin + null; + end; +end;~'; + end; + + procedure drop_test_case_suites is + pragma autonomous_transaction; + begin + for r in ( + select object_name, object_type + from user_objects + where object_name in ( + 'TC_DISCOUNT_PLSQL', 'TC_DISCOUNT_JSON', 'TC_DISCOUNT_SOURCE', 'TC_DISCOUNT_CURSOR', + 'TC_INLINE', 'TC_SOURCES', 'TC_JSON_SOURCE', 'TC_CURSOR_SOURCE', 'TC_TIMES', 'GET_DISCOUNT' + ) + and object_type in ('PACKAGE', 'FUNCTION') + ) loop + execute immediate 'drop ' || r.object_type || ' ' || r.object_name; + end loop; + execute immediate 'drop table test_case_rows purge'; + execute immediate 'drop type test_case_numbers'; + execute immediate 'drop type test_case_pair'; + end; + + -- other NLS settings and session time zone than usual, to show that test cases don't depend on them + procedure set_other_session is + begin + g_time_zone := sessiontimezone; + select ut3_develop.ut_key_value_pair(parameter, value) + bulk collect into g_nls_parameters + from nls_session_parameters + where parameter in ('NLS_DATE_FORMAT', 'NLS_TIMESTAMP_FORMAT', 'NLS_TIMESTAMP_TZ_FORMAT', 'NLS_NUMERIC_CHARACTERS'); + execute immediate q'[alter session set time_zone = '+02:00']'; + execute immediate q'[alter session set nls_date_format = 'DD.MM.YYYY']'; + execute immediate q'[alter session set nls_timestamp_format = 'DD.MM.YYYY HH24:MI:SSXFF']'; + execute immediate q'[alter session set nls_timestamp_tz_format = 'DD.MM.YYYY HH24:MI:SSXFF TZR']'; + execute immediate q'[alter session set nls_numeric_characters = ',.']'; + end; + + procedure restore_session is + begin + execute immediate 'alter session set time_zone = ''' || g_time_zone || ''''; + for i in 1 .. g_nls_parameters.count loop + execute immediate 'alter session set ' || g_nls_parameters(i).key || ' = ''' || g_nls_parameters(i).value || ''''; + end loop; + end; + + function run_report(a_path varchar2) return clob is + l_results ut3_develop.ut_varchar2_list; + begin + select * bulk collect into l_results from table(ut3_develop.ut.run(a_path)); + return ut3_tester_helper.main_helper.table_to_clob(l_results); + end; + + -- the lines of the report that start with a_prefix, without execution times + function report_lines(a_path varchar2, a_prefix varchar2) return varchar2 is + l_results ut3_develop.ut_varchar2_list; + l_result varchar2(32767); + begin + select * bulk collect into l_results from table(ut3_develop.ut.run(a_path)); + for i in 1 .. l_results.count loop + if ltrim(l_results(i)) like a_prefix || '%' then + l_result := l_result || case when l_result is not null then chr(10) end + || regexp_replace(trim(l_results(i)), ' \[[^]]*\]( \(FAILED - [0-9]+\))?$', '\1'); + end if; + end loop; + return l_result; + end; + + procedure discount_json_arguments is + begin + ut.expect(report_lines('tc_discount_json', 'Discount for')).to_equal(c_discount_cases); + ut.expect(run_report('tc_discount_json')).to_be_like('%4 tests, 0 failed, 0 errored, 0 disabled, 0 warning(s)%'); + end; + + procedure discount_json_source is + begin + ut.expect(report_lines('tc_discount_source', 'Discount for')).to_equal(c_discount_cases); + ut.expect(run_report('tc_discount_source')).to_be_like('%4 tests, 0 failed, 0 errored, 0 disabled, 0 warning(s)%'); + end; + + procedure discount_cursor_source is + begin + ut.expect(report_lines('tc_discount_cursor', 'Discount for')).to_equal(c_discount_cases); + ut.expect(run_report('tc_discount_cursor')).to_be_like('%4 tests, 0 failed, 0 errored, 0 disabled, 0 warning(s)%'); + end; + + procedure discount_independent_of_nls is + l_lines varchar2(32767); + begin + set_other_session(); + for r in ( + select column_value suite + from table(ut3_develop.ut_varchar2_list( + 'tc_discount_json', 'tc_discount_source', 'tc_discount_cursor' + )) + ) loop + l_lines := report_lines(r.suite, 'Discount for'); + ut.expect(l_lines, r.suite).to_equal(c_discount_cases); + end loop; + restore_session(); + exception + when others then + restore_session(); + raise; + end; + + procedure testcase_runs_each_case is + begin + ut.expect(report_lines('tc_inline.half', 'Half of')).to_equal( + 'Half of 2000 is 1000' || chr(10) || + 'Half of 10 is 5' || chr(10) || + 'Half of 3 is 2 (FAILED - 1)' || chr(10) || + 'Half of 8 is 4' || chr(10) || + 'Half of 1 is 1 (FAILED - 2)' + ); + end; + + procedure testcase_by_path is + begin + ut.expect(run_report('tc_inline.half')).to_be_like('%5 tests, 2 failed, 0 errored%'); + end; + + procedure testcase_single_case_by_path is + begin + ut.expect(run_report('tc_inline.half[5]')).to_be_like('%Half of 1 is 1 [%1 tests, 1 failed, 0 errored%'); + ut.expect(run_report(':tc_inline.half[2]')).to_be_like('%Half of 10 is 5 [%1 tests, 0 failed, 0 errored%'); + ut.expect(run_report('tc_inline.half[4]')).to_be_like('%Half of 8 is 4 [%1 tests, 0 failed, 0 errored%'); + end; + + procedure testcase_number_on_package is + l_results ut3_develop.ut_varchar2_list; + begin + select * bulk collect into l_results from table(ut3_develop.ut.run('tc_inline[2]')); + end; + + procedure testcase_reported_names is + l_results ut3_develop.ut_varchar2_list; + begin + ut.expect(run_report('tc_inline.half')).to_be_like('%Failures:%1) half[3]%2) half[5]%'); + + select * bulk collect into l_results + from table(ut3_develop.ut.run('tc_inline.half', ut3_develop.ut_junit_reporter())); + ut.expect(ut3_tester_helper.main_helper.table_to_clob(l_results)).to_be_like( + '%, 0BEE, <%TEST_CASE_NUMBERS>) [%1 tests, 0 failed, 0 errored%' + ); + end; + + procedure source_cursor_too_many_columns is + begin + ut.expect(run_report('tc_cursor_source.too_many_columns')).to_be_like( + '%The --%testcasesource function get_wide returned more columns than can be passed to the test procedure.%1 tests, 0 failed, 1 errored%' + ); + end; + + procedure source_cursor_position_count is + begin + ut.expect(run_report('tc_cursor_source.position_count')).to_be_like( + '%The --%testcasesource function get_three returned 3 column(s) and none is named like a parameter, but the test procedure has 2 parameter(s);%1 tests, 0 failed, 1 errored%' + ); + end; + + procedure source_cursor_misspelled_column is + begin + ut.expect(run_report('tc_cursor_source.misspelled_column')).to_be_like( + '%The --%testcasesource function get_misspelled returned column A_HALV, which is no parameter of the test procedure and isn''t used in the description.%1 tests, 0 failed, 1 errored%' + ); + end; + + procedure source_cursor_missing_column is + begin + ut.expect(run_report('tc_cursor_source.missing_column')).to_be_like( + '%The --%testcasesource function get_amount returned no column for parameter A_HALF, which has no default value.%1 tests, 0 failed, 1 errored%' + ); + end; + + procedure source_cursor_duplicate_column is + begin + ut.expect(run_report('tc_cursor_source.duplicate_column')).to_be_like( + '%The --%testcasesource function get_duplicate returned columns A_AMOUNT and a_amount for the same parameter A_AMOUNT.%1 tests, 0 failed, 1 errored%' + ); + end; + + procedure source_cursor_lower_case_column is + begin + ut.expect(run_report('tc_cursor_source.lower_case_column')).to_be_like('%Lower case 4 [%1 tests, 0 failed, 0 errored%'); + end; + + procedure source_cursor_overloaded is + begin + ut.expect(run_report('tc_cursor_source.overloaded')).to_be_like( + '%The --%testcasesource function get_amount can''t be used with the overloaded procedure OVERLOADED.%1 tests, 0 failed, 1 errored%' + ); + end; + + procedure source_json_values_dont_fit is + begin + ut.expect(run_report('tc_json_source.mismatching')).to_be_like( + '%mismatching[2]%ORA-01722%' || + 'mismatching[3]%Invalid JSON test case: 4 value(s) given, but the procedure has 2 parameter(s).%' || + 'mismatching[4]%Invalid JSON test case: the procedure has no parameter a_x.%' || + 'mismatching[5]%Invalid JSON test case: parameter A_NUMBER is given twice.%' || + 'mismatching[6]%' || + 'mismatching[7]%Invalid JSON test case: no value for parameter A_NUMBER, which has no default value.%' || + '7 tests, 0 failed, 6 errored%' + ); + end; + + procedure source_json_long_values is + begin + ut.expect(run_report('tc_json_source.long_values')).to_be_like('%1 tests, 0 failed, 0 errored%'); + end; + + procedure source_no_description is + begin + ut.expect(run_report('tc_json_source.no_description')).to_be_like('%no_description[1] [%1 tests, 0 failed, 0 errored%'); + end; + + procedure source_cursor_by_name is + begin + ut.expect(report_lines('tc_cursor_source.by_name', 'Cursor case')).to_equal( + 'Cursor case today with limit 100' || chr(10) || + 'Cursor case tomorrow with limit 200' + ); + ut.expect(run_report('tc_cursor_source.by_name')).to_be_like('%2 tests, 0 failed, 0 errored%'); + end; + + procedure source_cursor_by_position is + begin + ut.expect(run_report('tc_cursor_source.by_position')).to_be_like( + '%Position: half of 4 is 2 [%Position: half of 10 is 5 [%2 tests, 0 failed, 0 errored%' + ); + end; + + procedure source_cursor_snapshot is + begin + ut.expect(run_report('tc_cursor_source.snapshot')).to_be_like('%3 tests, 0 failed, 0 errored%'); + end; + + procedure source_cursor_no_rows is + begin + ut.expect(run_report('tc_cursor_source.no_rows')).to_be_like( + '%The --%testcasesource function returned no test cases.%0 tests, 0 failed, 0 errored, 0 disabled, 1 warning(s)%' + ); + end; + + procedure source_cursor_unsupported_column is + begin + ut.expect(run_report('tc_cursor_source.unsupported_column')).to_be_like( + '%The --%testcasesource function get_xml returned column A_XML, which has a data type that can''t be passed to the test: XMLTYPE.%' || + '1 tests, 0 failed, 1 errored%' + ); + end; + + procedure source_cursor_column_doesnt_fit is + begin + ut.expect(run_report('tc_cursor_source.column_doesnt_fit')).to_be_like( + '%The --%testcasesource function get_wrong_column returned column A_PAIR of type NUMBER, which can''t be passed to parameter A_PAIR of type %.TEST_CASE_PAIR.%1 tests, 0 failed, 1 errored%' + ); + end; + + procedure source_cursor_many_rows is + begin + ut.expect(run_report('tc_cursor_source.many_rows')).to_be_like('%300 tests, 0 failed, 0 errored%'); + end; + + $if dbms_db_version.version >= 23 $then + procedure source_cursor_booleans is + begin + ut.expect(run_report('tc_cursor_source.booleans')).to_be_like( + '%Flag true is yes [%Flag false is no [%Flag null is null [%3 tests, 0 failed, 0 errored%' + ); + end; + $end + + procedure times_json_and_cursor_alike is + begin + set_other_session(); + ut.expect(run_report('tc_times.json_strings'), 'JSON').to_be_like('%2 tests, 0 failed, 0 errored%'); + ut.expect(run_report('tc_times.cursor_values'), 'cursor').to_be_like('%1 tests, 0 failed, 0 errored%'); + restore_session(); + exception + when others then + restore_session(); + raise; + end; + + procedure times_date_only is + begin + set_other_session(); + ut.expect(run_report('tc_times.date_only')).to_be_like('%1 tests, 0 failed, 0 errored%'); + restore_session(); + exception + when others then + restore_session(); + raise; + end; + + procedure times_invalid_format is + begin + ut.expect(run_report('tc_times.other_format')).to_be_like( + '%other_format[1]%ORA-01%1 tests, 0 failed, 1 errored%' + ); + end; + +end; +/ diff --git a/test/ut3_user/api/test_ut_test_cases.pks b/test/ut3_user/api/test_ut_test_cases.pks new file mode 100644 index 000000000..12716ffda --- /dev/null +++ b/test/ut3_user/api/test_ut_test_cases.pks @@ -0,0 +1,191 @@ +create or replace package test_ut_test_cases is + --%suite(test cases: --%testcase and --%testcasesource) + --%suitepath(utplsql.test_user.api) + + --%beforeall(create_test_case_suites) + --%afterall(drop_test_case_suites) + + procedure create_test_case_suites; + procedure drop_test_case_suites; + + --%context(the examples of discussion #1326) + + --%test(Runs test cases given as JSON arrays and objects) + procedure discount_json_arguments; + + --%test(Runs test cases returned as json_array_t) + procedure discount_json_source; + + --%test(Runs test cases returned as cursor) + procedure discount_cursor_source; + + --%test(Gives the same results when NLS settings and session time zone differ) + procedure discount_independent_of_nls; + + --%endcontext + + --%context(--%testcase) + + --%test(Runs each test case as a separate test, from JSON arrays and objects) + procedure testcase_runs_each_case; + + --%test(Runs all test cases of a procedure given by path) + procedure testcase_by_path; + + --%test(Runs a single test case given by path) + procedure testcase_single_case_by_path; + + --%test(Raises invalid path format when a test case number follows a package name) + --%throws(ut3_develop.ut_utils.gc_invalid_path_format) + procedure testcase_number_on_package; + + --%test(Reports each test case under its own name in all reporters) + procedure testcase_reported_names; + + --%test(Passes JSON strings with quotes, non-ASCII characters and unicode escapes) + procedure testcase_strings; + + --%test(Uses the default of parameters missing in a JSON object or array) + procedure testcase_defaults; + + --%test(Converts JSON strings to numbers and numbers to strings) + procedure testcase_json_conversions; + + --%test(Passes JSON booleans and reports other values for BOOLEAN parameters as errors) + procedure testcase_json_booleans; + + --%test(Passes object types and collections from JSON, requiring a JSON object or array with all attributes) + procedure testcase_json_objects; + + --%test(Reports a test case as errored when a parameter type can't be passed from JSON) + procedure testcase_json_unsupported_type; + + --%test(Reports JSON test cases of overloaded procedures as errored) + procedure testcase_json_overloaded; + + --%test(Skips a test case that is no JSON array or object with a warning) + procedure testcase_not_json; + + --%test(Reports test cases whose arguments don't fit the parameters as errored and runs the others) + procedure testcase_arguments_dont_fit; + + --%test(Converts JSON values to BINARY_DOUBLE, NVARCHAR2, intervals, RAW and CLOB) + procedure testcase_json_more_types; + + --%test(Runs empty JSON arrays and objects for procedures without parameters) + procedure testcase_without_parameters; + + --%test(Reports a JSON test case for a PL/SQL record parameter as errored, naming the type) + procedure testcase_json_record_parameter; + + --%test(Reports JSON test cases for package collections, JSON object types and BLOB as errored, naming the type) + procedure testcase_json_package_types; + + --%endcontext + + --%context(--%testcasesource returning JSON) + + --%test(Calls the function after beforeall and runs one test case per element) + procedure source_json_after_beforeall; + + --%test(Calls a function of another package and a function with default arguments) + procedure source_json_function_reference; + + --%test(Passes JSON built with the PL/SQL JSON API, with sysdate and constants) + procedure source_json_built; + + --%test(Gives a warning for an empty array, null and json_arrayagg over no rows with nvl) + procedure source_json_no_test_cases; + + --%test(Reports the test as errored when the function doesn't return a JSON array of arrays and objects) + procedure source_json_invalid_result; + + --%test(Reports the test as errored when the function doesn't exist, fails or returns another type than json_array_t or sys_refcursor) + procedure source_function_errors; + + --%test(Doesn't call the function of a disabled test) + procedure source_disabled; + + --%test(Reports JSON values that don't fit the parameters as errors of their test case) + procedure source_json_values_dont_fit; + + --%test(Passes long strings and clobs) + procedure source_json_long_values; + + --%test(Names a test case of a test without description by its procedure) + procedure source_no_description; + + --%test(Reports JSON test cases of an overloaded procedure as errored) + procedure source_json_overloaded; + + --%endcontext + + --%context(--%testcasesource returning a cursor) + + --%test(Passes columns by name, with sysdate, constants and object types, and uses other columns in the description) + procedure source_cursor_by_name; + + --%test(Passes columns by position when no column is named like a parameter) + procedure source_cursor_by_position; + + --%test(Passes the rows fetched before the first test case even when they are deleted) + procedure source_cursor_snapshot; + + --%test(Gives a warning when the cursor returns no rows) + procedure source_cursor_no_rows; + + --%test(Reports the test as errored when a column has a type that can't be passed) + procedure source_cursor_unsupported_column; + + --%test(Reports the test as errored when a column doesn't fit its parameter) + procedure source_cursor_column_doesnt_fit; + + --%test(Runs many test cases) + procedure source_cursor_many_rows; + + --%test(Passes columns of all supported types and shows them in the description) + procedure source_cursor_types; + + --%test(Reports the test as errored when the cursor has more columns than can be passed) + procedure source_cursor_too_many_columns; + + --%test(Reports the test as errored when no column is named like a parameter and the number of columns doesn't match) + procedure source_cursor_position_count; + + --%test(Reports the test as errored when a column is no parameter and isn't used in the description) + procedure source_cursor_misspelled_column; + + --%test(Reports the test as errored when a parameter without default has no column) + procedure source_cursor_missing_column; + + --%test(Reports the test as errored when two columns are named like the same parameter) + procedure source_cursor_duplicate_column; + + --%test(Matches column names to parameters not case-sensitive and uses defaults of parameters without column) + procedure source_cursor_lower_case_column; + + --%test(Reports the test as errored when the test procedure is overloaded) + procedure source_cursor_overloaded; + + $if dbms_db_version.version >= 23 $then + --%test(Passes BOOLEAN columns) + procedure source_cursor_booleans; + $end + + --%endcontext + + --%context(dates and times) + + --%test(Converts date and time strings of JSON like the values of a cursor) + procedure times_json_and_cursor_alike; + + --%test(Converts dates without time) + procedure times_date_only; + + --%test(Reports date strings in another format as errors of their test case) + procedure times_invalid_format; + + --%endcontext + +end; +/ From 103d006ceca64fe375f096593da6d85fb7c0665c Mon Sep 17 00:00:00 2001 From: Jakob Drees <32562853+WayneNani@users.noreply.github.com> Date: Sat, 28 Nov 2026 04:53:48 +0000 Subject: [PATCH 2/3] Apply the review of #1326 to parameterized tests - A --%testcasesource function returns json_array_t only; the cursor path, the type ut_anydata_list and the ANYDATA call are removed. - Values and keys beyond the parameters are ignored, so one source can serve several tests and values can be shown in the description only. The generated call reads object values by the position of their key and never contains a key. Keys match parameter names not case-sensitive, also quoted ones. - Every --%testcase annotation and every element of a source is a test: an invalid one errors when it runs instead of being skipped with a warning, and never stops the run. Only an empty --%testcase gives a warning. Identical test cases each run. - Test cases of a procedure without parameters error. - A placeholder that refers to no value appends the values to the description, e.g. "Not existing {reference} (4, 2)"; placeholders are replaced in a single pass and by name not case-sensitive. - pkg.test[n] runs test case n of a --%testcasesource test: the path selects the test, the function is called and only case n runs. A number beyond the test cases gives a warning; a test that is also selected as a whole runs all its test cases. Co-Authored-By: Claude Opus 5.5 --- docs/userguide/annotations.md | 131 ++-- docs/userguide/running-unit-tests.md | 2 +- source/core/types/ut_anydata_list.tps | 19 - source/core/types/ut_executable.tpb | 49 +- source/core/types/ut_executable.tps | 5 +- source/core/types/ut_suite.tpb | 44 +- source/core/types/ut_test.tpb | 437 ++------------ source/core/types/ut_test.tps | 2 +- source/core/ut_suite_builder.pkb | 88 +-- source/core/ut_suite_cache_macros.pkb | 22 +- source/core/ut_suite_cache_macros.pks | 10 +- source/core/ut_suite_cache_manager.pkb | 32 +- source/core/ut_suite_cache_manager.pks | 10 + source/core/ut_suite_manager.pkb | 10 +- source/core/ut_test_case_json.pkb | 64 +- source/core/ut_test_case_json.pks | 16 +- source/core/ut_test_case_values.pkb | 35 +- source/core/ut_test_case_values.pks | 25 +- source/core/ut_utils.pkb | 53 +- source/core/ut_utils.pks | 7 +- source/create_grants.sql | 1 - source/install.sql | 1 - source/uninstall_objects.sql | 2 - test/ut3_tester/core/test_suite_builder.pkb | 81 +-- test/ut3_tester/core/test_suite_builder.pks | 11 +- test/ut3_tester/core/test_ut_utils.pkb | 33 +- test/ut3_tester/core/test_ut_utils.pks | 10 +- test/ut3_user/api/test_ut_test_cases.pkb | 638 +++++--------------- test/ut3_user/api/test_ut_test_cases.pks | 87 +-- 29 files changed, 565 insertions(+), 1360 deletions(-) delete mode 100644 source/core/types/ut_anydata_list.tps diff --git a/docs/userguide/annotations.md b/docs/userguide/annotations.md index 75e24ab69..e2b97cfb8 100644 --- a/docs/userguide/annotations.md +++ b/docs/userguide/annotations.md @@ -128,7 +128,7 @@ end; | `--%displayname( )` | Package/procedure | Human-readable and meaningful description of a context/suite/test. Overrides the `` provided with `suite`/`test`/`context` annotation. This annotation is redundant and might be removed in future releases. | | `--%test( )` | Procedure | Denotes that the annotated procedure is a unit test procedure. Optional test description can be provided (see `displayname`). | | `--%testcase( )` | Procedure | Runs the annotated `%test` procedure once per `%testcase` annotation, passing the JSON values to the procedure. See [Testcase](#testcase). | -| `--%testcasesource( )` | Procedure | Runs the annotated `%test` procedure once per test case returned by the function (JSON array or cursor). See [Testcasesource](#testcasesource). | +| `--%testcasesource( )` | Procedure | Runs the annotated `%test` procedure once per test case returned by the function as JSON array. See [Testcasesource](#testcasesource). | | `--%throws( [,...] )` | Procedure | Denotes that the annotated test procedure must throw one of the exceptions provided. Supported forms of exceptions are: numeric literals, numeric constant names, exception constant names, predefined Oracle exception names. | | `--%beforeall` | Procedure | Denotes that the annotated procedure should be executed once before all elements of the suite. | | `--%beforeall( [[.].][,...] )` | Package | Denotes that the mentioned procedure(s) should be executed once before all elements of the suite. | @@ -348,10 +348,11 @@ Use it when the same check needs to be done for several inputs, for example boun - Each `--%testcase` annotation becomes a separate test. It is reported, counted and run on its own, with its own `--%beforeeach`/`--%beforetest`/`--%aftertest`/`--%aftereach` calls and its own rollback. - The arguments are a JSON array or a JSON object: an array passes its values by position, an object passes its values to the parameters named like its keys (not case-sensitive). Parameters with default values can be omitted from an object, and at the end of an array. + Values beyond the parameters of an array and keys that are no parameter are not passed, but can be used in the description. - The values are converted to the data types of the parameters when the test case runs, see [JSON values](#json-values). Dates and times are strings in ISO 8601 format, independent of the NLS settings of the session, see [Dates and times](#dates-and-times). - JSON values are literals: they can't use `sysdate`, constants, function calls or object constructors. - For such values, use [`--%testcasesource`](#testcasesource) with a function that builds the JSON or returns a cursor. + For such values, use [`--%testcasesource`](#testcasesource) with a function that builds the JSON. - The test cases of a procedure are named `[1]`, `[2]`, ... in the order of the annotations. Running the procedure by path, for example `ut.run('test_get_discount.discount_by_customer_type')`, runs all of its test cases; `ut.run('test_get_discount.discount_by_customer_type[2]')` runs only the second one. - `--%tags`, `--%throws`, `--%rollback`, `--%disabled` and `--%beforetest`/`--%aftertest` of the test procedure apply to every test case. @@ -359,7 +360,9 @@ The description of the `--%test` annotation can refer to the arguments of a test - `{1}`, `{2}`, ... is replaced with the first, second, ... value - `{}` is replaced with the value passed to that parameter, by key or by position -- without any placeholder, the values are appended to the description in brackets +- `{}` of a JSON object is replaced with its value, also for a key that is no parameter +- without any placeholder, or with a placeholder that refers to no value, the values are appended to the description in brackets, + e.g. `Not existing {reference} (4, 2)` Strings are shown without quotes, `null` as `null`. Values longer than 100 characters are shortened. @@ -440,24 +443,23 @@ Finished in .041927 seconds ``` The whole annotation must fit in one line and end with the closing bracket; a comment after the annotation is not allowed. -Using `--%testcase` on a procedure without `--%test` gives a warning and the annotation is ignored. +Using `--%testcase` on a procedure without `--%test`, or without arguments, gives a warning and the annotation is ignored. -When the suite is built, the arguments of each test case are checked: they must be a valid JSON array or object, -and the number of values, the keys and the parameters without default value must fit the parameters of the test procedure. -A test case with invalid arguments gives a warning and is skipped; the numbers of the other test cases don't change. -Types are checked when the test case runs: a value that can't be converted to its parameter type makes only that test case error. +Every `--%testcase` annotation is a test, also one with invalid arguments: it is listed by `ut_runner.get_suites_info`, counted and run, +and errors with `ORA-20220` and a message that names the problem, while the other test cases run. A test case errors when +its arguments are no JSON array or object, a parameter without default value gets no value, a parameter is given twice +(keys that differ only in case), a value can't be converted to its parameter type, or the procedure has no parameters. +A misconfigured test case never stops the run of the suite. +Identical test cases are allowed; each of them runs. ### Testcasesource The `--%testcasesource` annotation runs a `--%test` procedure once for each test case returned by a function. It suits many test cases and test cases computed with `sysdate`, constants or data from tables. -The function takes no arguments (or only arguments with default values) and returns either - -- a `json_array_t`: each element is a test case, given as a JSON array or JSON object like the JSON of `--%testcase`, or -- a `sys_refcursor`: each row is a test case. Columns named like a parameter of the test procedure (not case-sensitive) are passed to that parameter; - other columns are not passed, but can be used in the description. If no column is named like a parameter, all columns are passed by position, - see [Cursor columns](#cursor-columns). +The function takes no arguments (or only arguments with default values) and returns a `json_array_t`: +each element is a test case, given as a JSON array or JSON object like the JSON of `--%testcase`. +As values and keys beyond the parameters are not passed, one function can provide the test cases of several tests. The function is given by name: `discount_cases` for a function in the test package, `.` or `..` for a function elsewhere. @@ -483,7 +485,7 @@ end; / ``` -A function returning JSON (the procedure `discount_by_customer_type` is the same as above): +The function (the procedure `discount_by_customer_type` is the same as above): ```sql linenums="1" function discount_cases return json_array_t is @@ -513,46 +515,7 @@ A function returning JSON (the procedure `discount_by_customer_type` is the same end; ``` -A function returning a cursor (declared as `function discount_cases return sys_refcursor;`): - -```sql linenums="1" - function discount_cases return sys_refcursor is - l_cursor sys_refcursor; - begin - open l_cursor for - select 500 as a_order_total, - 'REGULAR' as a_customer_type, - to_date('2026-03-15 14:30:00', 'yyyy-mm-dd hh24:mi:ss') as a_order_date, - to_timestamp('2026-03-01 00:00:00.000000', 'yyyy-mm-dd hh24:mi:ss.ff') as a_promo_start, - to_timestamp_tz('2026-03-31 23:59:59.999999 +02:00', 'yyyy-mm-dd hh24:mi:ss.ff tzh:tzm') as a_promo_end, - 0.05 as a_expected - from dual - union all - select 1000, 'REGULAR', - to_date('2026-04-01 09:00:00', 'yyyy-mm-dd hh24:mi:ss'), - to_timestamp('2026-03-01 00:00:00.000000', 'yyyy-mm-dd hh24:mi:ss.ff'), - to_timestamp_tz('2026-03-31 23:59:59.999999 +02:00', 'yyyy-mm-dd hh24:mi:ss.ff tzh:tzm'), - 0.1 - from dual - union all - select 50, 'VIP', - to_date('2026-03-20 10:00:00', 'yyyy-mm-dd hh24:mi:ss'), - to_timestamp('2026-03-01 00:00:00.000000', 'yyyy-mm-dd hh24:mi:ss.ff'), - to_timestamp_tz('2026-03-31 23:59:59.999999 -05:00', 'yyyy-mm-dd hh24:mi:ss.ff tzh:tzm'), - 0.25 - from dual - union all - select null, 'REGULAR', - to_date('2026-02-28 23:59:59', 'yyyy-mm-dd hh24:mi:ss'), - to_timestamp('2026-03-01 00:00:00.000000', 'yyyy-mm-dd hh24:mi:ss.ff'), - to_timestamp_tz('2026-03-31 23:59:59.999999 +02:00', 'yyyy-mm-dd hh24:mi:ss.ff tzh:tzm'), - 0 - from dual; - return l_cursor; - end; -``` - -All variants give the same test cases and descriptions as the `--%testcase` example above. +It gives the same test cases and descriptions as the `--%testcase` example above. - The function is called when the suite runs, after its `--%beforeall` procedures, so it sees the data they create. It is called once, and the test cases it returns are kept in memory until they have run, so changes to the data in `--%beforeeach`, `--%beforetest` or earlier test cases don't affect later test cases. @@ -560,36 +523,21 @@ All variants give the same test cases and descriptions as the `--%testcase` exam which can use `sysdate`, constants and data from tables. `json_arrayagg` returns `null` when there are no rows, and `json_array_t` can't parse `null`, so wrap it with `nvl`: `return json_array_t(nvl(l_json, '[]'));`. A function that returns `null` has no test cases. - Each test case becomes a separate test, named `[1]`, `[2]`, ... in the order the function returns them. Each test case is rolled back as usual. -- The description can refer to the values of a test case with `{1}`, `{2}`, ... (position) and `{}` (JSON key, column name, - or for the values of a JSON array the name of the parameter they are passed to). - Without any placeholder, the values are appended to the description in brackets. Values of a cursor are shown like in JSON: - dates and times in ISO 8601 format and numbers with a leading zero, e.g. `0.05`. -- If the function fails, doesn't exist, returns another type than `json_array_t` or `sys_refcursor`, or returns an element that is neither a JSON array nor a JSON object, - the test is reported as errored. - If it returns no test cases (an empty array, `null` or no rows), the suite gets a warning. +- The description can refer to the values of a test case like the description of `--%testcase`: `{1}`, `{2}`, ... (position) and `{}` + (JSON key, or for the values of a JSON array the name of the parameter they are passed to). +- If the function fails, doesn't exist or returns another type than `json_array_t`, the test is reported as errored. + If it returns no test cases (an empty array or `null`), the suite gets a warning. +- Each element is a test case, also an invalid one: an element that is no JSON array or object, or whose values don't fit the parameters, + makes only that test case error, as described for `--%testcase`. - A disabled test doesn't call its function. - `--%testcasesource` can't be combined with `--%testcase` on the same procedure. -- Running a single test case by path, for example `ut.run('test_get_discount.discount_by_customer_type[2]')`, is not supported, as the test cases are only known when the suite runs. -- Reporters that list all tests before the run, such as `ut_realtime_reporter`, list the test once, as its test cases are not known yet. - -#### Cursor columns - -The columns of a cursor are checked against the parameters of the test procedure before the first test case runs. -Each of the following makes the test error with `ORA-20220` and a message that names the column or parameter: - -- a column that is not named like a parameter and isn't used in the description (`{}` or `{}`), - so that a misspelled column name doesn't silently leave its parameter at the default value -- a parameter without default value that has no column -- two columns named like the same parameter, e.g. `a_amount` and `"a_amount"` -- no column named like a parameter, and the number of columns differs from the number of parameters -- a column whose type can't be passed to its parameter: object types and collections must be of the parameter type, - `BOOLEAN` columns only fit `BOOLEAN` parameters, and other values don't fit object type, collection, record or `BOOLEAN` parameters. - Other values are converted by PL/SQL; a value that can't be converted, for example `'abc'` for a `NUMBER`, makes only its test case error. -- an overloaded test procedure - -Cursor columns can have these data types: `VARCHAR2`, `CHAR`, `NVARCHAR2`, `NCHAR`, `NUMBER`, `BINARY_FLOAT`, `BINARY_DOUBLE`, `DATE`, `TIMESTAMP` (also with (local) time zone), -`INTERVAL`, `CLOB`, `NCLOB`, `BLOB`, `RAW`, `BOOLEAN` (Oracle 23 and later) and object types and collections that are not owned by `SYS`. -The values keep their type. Other types, such as `XMLTYPE`, make the test error with `ORA-20220`. +- `ut_runner.get_suites_info` and reporters that list all tests before the run, such as `ut_realtime_reporter`, list the test once, + as its test cases are only known when the suite runs; the test cases are reported when they run. +- A single test case can be run by path, for example `ut.run('test_get_discount.discount_by_customer_type[2]')`: + the function is called, and only its second test case runs. The number refers to the order in which the function returns + the test cases, so it selects the same test case only as long as the function returns the same test cases in the same order. + A number beyond the test cases the function returns gives a warning. When the test is also selected as a whole + (e.g. by its package), all its test cases run. #### JSON values @@ -608,18 +556,23 @@ JSON values of `--%testcase` and `--%testcasesource` are converted to the data t - `null` passes `NULL` for every type. - A value that can't be converted, for example `"abc"` for a `NUMBER`, a value that is no JSON object for an object type or no JSON array for a collection, - or an object with a missing or unknown attribute, makes that test case error; the other test cases run. + or a JSON object for an object type with a missing or unknown attribute, makes that test case error; the other test cases run. So does a test case without value for a parameter that has no default value. - Other parameter types, such as `BLOB`, `XMLTYPE`, records and PL/SQL collections, can't be passed from JSON; such test cases error with `ORA-20220`. - JSON test cases can't be used with overloaded test procedures. +- Keys and values are passed as data: they never become part of the code that calls the test procedure, + so quotes or SQL in a key or value can't change that code. The following was decided on purpose (see [discussion #1326](https://github.com/utPLSQL/utPLSQL/discussions/1326)): -- **A JSON key that is no parameter of the test procedure is an error**, also when the key is meant only for the description. - A misspelled key would otherwise silently leave its parameter at the default value, and the test would check something else than it says. - Values for the description only can be returned by a cursor, whose extra columns are not passed to the procedure. -- **A `--%testcasesource` function returns `json_array_t`, not JSON text** (`clob`, `varchar2`). The type ensures that the function returns a JSON array: - invalid JSON or a JSON object raise an error in the function itself, where it is easy to find. +- **Values and keys beyond the parameters of the test procedure are ignored**, so that one `--%testcasesource` function can serve + several tests, and values that are only shown in the description can be part of a test case. + As a consequence, a misspelled key is not passed: its parameter gets its default value or, without default, the test case errors. +- **A `--%testcasesource` function returns `json_array_t`**, not JSON text (`clob`, `varchar2`) or a cursor. The type ensures that the function returns a JSON array: + invalid JSON or a JSON object raise an error in the function itself, where it is easy to find. JSON also passes values + by name or by position in a single, explicit way, and SQL can still build the JSON (`json_arrayagg`, `json_object`). +- **A misconfigured test case is an errored test**, not a warning: every `--%testcase` annotation and every element returned by + a `--%testcasesource` function counts as a test. #### Dates and times diff --git a/docs/userguide/running-unit-tests.md b/docs/userguide/running-unit-tests.md index f66745429..fa217a1dc 100644 --- a/docs/userguide/running-unit-tests.md +++ b/docs/userguide/running-unit-tests.md @@ -121,7 +121,7 @@ begin ut.run('hr.test_apply_bonus.bonus_for_amount[2]'); end; ``` -Executes only the second test case of the test procedure _hr.test_apply_bonus.bonus_for_amount_, see [Testcase](annotations.md#testcase). +Executes only the second test case of the test procedure _hr.test_apply_bonus.bonus_for_amount_, see [Testcase](annotations.md#testcase) and [Testcasesource](annotations.md#testcasesource). ```sql linenums="1" diff --git a/source/core/types/ut_anydata_list.tps b/source/core/types/ut_anydata_list.tps deleted file mode 100644 index 2015ef862..000000000 --- a/source/core/types/ut_anydata_list.tps +++ /dev/null @@ -1,19 +0,0 @@ -create or replace noneditionable type ut_anydata_list as - /* - utPLSQL - Version 3 - Copyright 2016 - 2026 utPLSQL Project - - Licensed 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. - */ - table of sys.anydata -/ diff --git a/source/core/types/ut_executable.tpb b/source/core/types/ut_executable.tpb index dc0b25116..04f59baa3 100644 --- a/source/core/types/ut_executable.tpb +++ b/source/core/types/ut_executable.tpb @@ -57,7 +57,6 @@ create or replace noneditionable type body ut_executable is return boolean is l_statement varchar2(32767); l_call varchar2(32767); - l_values ut_anydata_list; l_json clob; l_call_error varchar2(32767); l_parse_error varchar2(32767); @@ -68,39 +67,6 @@ create or replace noneditionable type body ut_executable is l_start_transaction_id varchar2(250); l_end_transaction_id varchar2(250); - /* - Unpacks the argument values of a --%testcasesource test case, bound as :ut_values. - Object types and collections need a variable of their type; other values are read by the call itself. - */ - function get_test_case_call(a_values ut_anydata_list, a_call varchar2) return varchar2 is - l_declarations varchar2(32767); - l_unpacking varchar2(32767); - l_type anytype; - l_typecode pls_integer; - begin - for i in 1 .. a_values.count loop - -- the type code, as gettypename raises no_data_found for an NCLOB - l_typecode := a_values(i).gettype(l_type); - if l_typecode in (dbms_types.typecode_object, dbms_types.typecode_namedcollection, dbms_types.typecode_varray, dbms_types.typecode_table) then - l_declarations := l_declarations || - ' l_ut_value_' || i || ' "' || replace(a_values(i).gettypename(), '.', '"."') || '";' || chr(10); - l_unpacking := l_unpacking || - ' l_ut_rc := l_ut_values(' || i || ').' || - case when l_typecode = dbms_types.typecode_object then 'getobject' else 'getcollection' end || - '(l_ut_value_' || i || ');' || chr(10); - end if; - end loop; - return - 'declare' || chr(10) || - ' l_ut_values ' || ut_utils.ut_owner || '.ut_anydata_list := :ut_values;' || chr(10) || - ' l_ut_rc pls_integer;' || chr(10) || - l_declarations || - ' begin' || chr(10) || - l_unpacking || - ' ' || a_call || chr(10) || - ' end;'; - end; - function is_defined return boolean is l_result boolean := false; l_message_part varchar2(4000) := 'Call params for ' || self.executable_type || ' are not valid: '; @@ -161,21 +127,20 @@ create or replace noneditionable type body ut_executable is if self.call_source is not null then l_json := ut_test_case_values.get_json(a_item.path); if l_json is null then - l_call := self.form_name( a_skip_current_user_schema => true ) || '(' || self.call_arguments || ');'; - -- without its values (e.g. package state was reset) the test case errors when it reads them, instead of breaking the run - l_values := coalesce(ut_test_case_values.get_values(a_item.path), ut_anydata_list()); - l_call := get_test_case_call(l_values, l_call); + raise_application_error( + ut_utils.gc_invalid_test_case_source, 'The values of the test case are no longer available, e.g. as the session state was reset.' + ); end if; elsif self.call_arguments is not null then -- the arguments of a --%testcase are JSON l_json := self.call_arguments; - else - l_call := self.form_name( a_skip_current_user_schema => true ) || ';'; end if; if l_json is not null then l_call := ut_test_case_json.get_call( self.owner_name, self.object_name, self.procedure_name, self.form_name( a_skip_current_user_schema => true ), l_json ); + else + l_call := self.form_name( a_skip_current_user_schema => true ) || ';'; end if; exception when others then @@ -225,9 +190,7 @@ create or replace noneditionable type body ut_executable is **/ begin dbms_sql.parse(l_cursor_number, statement => l_statement, language_flag => dbms_sql.native); - if l_call_error is null and l_values is not null then - dbms_sql.bind_variable(l_cursor_number, 'ut_values', l_values); - elsif l_call_error is null and l_json is not null then + if l_call_error is null and l_json is not null then dbms_sql.bind_variable(l_cursor_number, 'ut_json', l_json); end if; dbms_sql.bind_variable(l_cursor_number, 'a_error_stack', to_char(null), 32767); diff --git a/source/core/types/ut_executable.tps b/source/core/types/ut_executable.tps index 4f80f0beb..44545ce86 100644 --- a/source/core/types/ut_executable.tps +++ b/source/core/types/ut_executable.tps @@ -31,8 +31,7 @@ create or replace noneditionable type ut_executable under ut_event_item( */ seq_no integer, /** - * Arguments passed to the procedure: the JSON array or object of a --%testcase, e.g. ["VIP", 2000], - * or for a row of a --%testcasesource cursor the generated argument list that reads its values + * Arguments passed to the procedure: the JSON array or object of a --%testcase, e.g. ["VIP", 2000] */ call_arguments varchar2(4000 char), /** @@ -40,7 +39,7 @@ create or replace noneditionable type ut_executable under ut_event_item( */ call_source varchar2(4000 char), /** - * Number of the test case (element or row) the call_source function returned; null for the test that is not yet split + * Number of the test case (element of the JSON array) the call_source function returned; null for the test that is not yet split * into its test cases. The values of the test case are kept in ut_test_case_values. */ call_source_row integer, diff --git a/source/core/types/ut_suite.tpb b/source/core/types/ut_suite.tpb index 63ef50ce2..900f57fbe 100644 --- a/source/core/types/ut_suite.tpb +++ b/source/core/types/ut_suite.tpb @@ -46,9 +46,10 @@ create or replace noneditionable type body ut_suite as -- the --%testcasesource functions run after beforeall, so they see the data that beforeall created procedure execute_with_test_case_sources is - l_items ut_suite_items := ut_suite_items(); - l_test ut_test; - l_cases ut_suite_items; + l_items ut_suite_items := ut_suite_items(); + l_test ut_test; + l_cases ut_suite_items; + l_filter ut_integer_list; procedure add_item(a_item ut_suite_item) is begin @@ -68,22 +69,35 @@ create or replace noneditionable type body ut_suite as add_item(l_test); end; if l_cases is not null then + -- the test cases the run selects by path, e.g. "pkg.test[2]"; all when empty + l_filter := ut_test_case_values.get_case_filter(l_test.object_owner, l_test.path); if l_cases.count = 0 then self.put_warning('The --%testcasesource function returned no test cases.', l_test.name, l_test.line_no); end if; + for j in 1 .. l_filter.count loop + if l_filter(j) > l_cases.count then + self.put_warning( + 'Test case ' || l_filter(j) || ' doesn''t exist, the --%testcasesource function returned ' + || l_cases.count || ' test case(s).', + l_test.name, l_test.line_no + ); + end if; + end loop; for j in 1 .. l_cases.count loop - begin - l_cases(j).do_execute(); - exception - when others then - -- don't keep the values of the test cases that won't run - for k in j .. l_cases.count loop - ut_test_case_values.remove_values(l_cases(k).path); - end loop; - raise; - end; - ut_test_case_values.remove_values(l_cases(j).path); - add_item(l_cases(j)); + if l_filter.count = 0 or j member of l_filter then + begin + l_cases(j).do_execute(); + exception + when others then + -- don't keep the values of the test cases that won't run + for k in j .. l_cases.count loop + ut_test_case_values.remove_json(l_cases(k).path); + end loop; + raise; + end; + add_item(l_cases(j)); + end if; + ut_test_case_values.remove_json(l_cases(j).path); end loop; end if; else diff --git a/source/core/types/ut_test.tpb b/source/core/types/ut_test.tpb index 8dfb4c00e..1ddc62b8e 100644 --- a/source/core/types/ut_test.tpb +++ b/source/core/types/ut_test.tpb @@ -187,6 +187,11 @@ create or replace noneditionable type body ut_test as l_function varchar2(128 char); l_function_call varchar2(1000 char); l_return_type ut_metadata.t_parameter; + l_parameters ut_metadata.tt_parameters; + l_names ut_varchar2_list := ut_varchar2_list(); + l_json clob; + l_array json_array_t; + l_test ut_test; l_result ut_suite_items := ut_suite_items(); procedure raise_invalid(a_message varchar2) is @@ -195,386 +200,6 @@ create or replace noneditionable type body ut_test as ut_utils.gc_invalid_test_case_source, 'The --%testcasesource function ' || self.item.call_source || ' ' || a_message || '.' ); end; - - function add_test_case(a_row_no integer, a_description varchar2, a_call_arguments varchar2 := null) return varchar2 is - l_test ut_test := self; - begin - l_test.name := self.name || '[' || a_row_no || ']'; - l_test.path := self.path || '[' || a_row_no || ']'; - l_test.description := a_description; - l_test.item.call_source_row := a_row_no; - l_test.item.call_arguments := a_call_arguments; - l_result.extend; - l_result(l_result.last) := l_test; - return l_test.path; - end; - - -- each element of the array is a test case; its JSON text is converted to the parameter types when the test case runs - procedure add_json_test_cases is - l_json clob; - l_element json_element_t; - l_array json_array_t; - l_parameters ut_metadata.tt_parameters := - ut_metadata.get_package_parameters(upper(self.item.owner_name), upper(self.item.object_name), upper(self.item.procedure_name)); - l_names ut_varchar2_list := ut_varchar2_list(); - begin - for i in 1 .. l_parameters.count loop - if l_parameters(i).overload = l_parameters(1).overload and l_parameters(i).parameter_name is not null then - l_names.extend; - l_names(l_names.last) := l_parameters(i).parameter_name; - end if; - end loop; - execute immediate - 'declare l_ut_cases json_array_t := ' || l_function_call || ';' || - ' begin if l_ut_cases is not null then :ut_json := l_ut_cases.to_clob(); else :ut_json := null; end if; end;' - using out l_json; - -- a function that returns null has no test cases - if l_json is null then - return; - end if; - l_array := json_array_t.parse(l_json); - for i in 0 .. l_array.get_size - 1 loop - l_element := l_array.get(i); - if not (l_element.is_array or l_element.is_object) then - raise_invalid('returned element ' || (i + 1) || ', which is neither a JSON array nor a JSON object'); - end if; - l_json := l_element.to_clob; - ut_test_case_values.set_json( - add_test_case(i + 1, ut_test_case_json.get_test_case_description(self.description, l_json, l_names)), l_json - ); - end loop; - end; - - -- the rows of the cursor are fetched once; each test case gets the values of its row as ANYDATA - procedure add_cursor_test_cases is - type tt_positions is table of pls_integer index by pls_integer; - l_parameters ut_metadata.tt_parameters := - ut_metadata.get_package_parameters(upper(self.item.owner_name), upper(self.item.object_name), upper(self.item.procedure_name)); - l_params ut_metadata.tt_parameters := ut_metadata.tt_parameters(); - l_cursor integer; - l_columns dbms_sql.desc_tab3; - l_count integer; - l_named boolean; - l_param_of tt_positions; -- column -> the parameter it is passed to, 0 for none - l_column_of tt_positions; -- parameter -> the column passed to it - l_index pls_integer; - l_arguments varchar2(4000 char); - l_argument varchar2(4000 char); - l_declarations varchar2(32767); - l_defines varchar2(32767); - l_fetches varchar2(32767); - l_values_code varchar2(32767); - l_display_code varchar2(32767); - l_values ut_anydata_list; - l_display ut_varchar2_list; - l_row_values ut_anydata_list; - l_row_display ut_varchar2_list; - l_names ut_varchar2_list := ut_varchar2_list(); - - -- columns are matched to parameters like JSON keys, not case-sensitive - function find_parameter(a_column_name varchar2) return pls_integer is - l_position pls_integer := l_params.first; - begin - while l_position is not null loop - if upper(l_params(l_position).parameter_name) = upper(a_column_name) then - return l_position; - end if; - l_position := l_params.next(l_position); - end loop; - return 0; - end; - - function is_in_description(a_column_name varchar2, a_position integer) return boolean is - begin - return nvl( - instr(self.description, '{' || a_column_name || '}') > 0 - or instr(self.description, '{' || lower(a_column_name) || '}') > 0 - or instr(self.description, '{' || a_position || '}') > 0, - false - ); - end; - - -- PL/SQL converts scalar values implicitly; object types, collections and BOOLEAN must match the parameter - function fits(a_column dbms_sql.desc_rec3, a_parameter ut_metadata.t_parameter) return boolean is - begin - return nvl( - case - when a_column.col_type = 109 then - a_parameter.type_owner = a_column.col_schema_name and a_parameter.type_name = a_column.col_type_name - and a_parameter.type_subname is null - when a_column.col_type = 252 then - a_parameter.data_type in ('BOOLEAN', 'PL/SQL BOOLEAN') - else - a_parameter.type_name is null and a_parameter.data_type not in ('BOOLEAN', 'PL/SQL BOOLEAN') - end, - false - ); - end; - - function parameter_type(a_parameter ut_metadata.t_parameter) return varchar2 is - begin - return nvl( - -- no nvl2: before Oracle 21 it exists only in SQL, not in PL/SQL - a_parameter.type_owner || case when a_parameter.type_owner is not null then '.' end || a_parameter.type_name - || case when a_parameter.type_subname is not null then '.' || a_parameter.type_subname end, - a_parameter.data_type - ); - end; - - function is_collection(a_column dbms_sql.desc_rec3) return boolean is - l_typecode all_types.typecode%type; - begin - select /*+ no_parallel */ typecode into l_typecode - from all_types - where owner = a_column.col_schema_name and type_name = a_column.col_type_name; - return l_typecode = 'COLLECTION'; - end; - - function declaration(a_column dbms_sql.desc_rec3) return varchar2 is - l_national boolean := a_column.col_charsetform = 2; - begin - return - case a_column.col_type - when 1 then case when l_national then 'nvarchar2(32767)' else 'varchar2(32767)' end - when 96 then case when l_national then 'nvarchar2(32767)' else 'varchar2(32767)' end - when 2 then 'number' - when 100 then 'binary_float' - when 101 then 'binary_double' - when 12 then 'date' - when 180 then 'timestamp(9)' - when 181 then 'timestamp(9) with time zone' - when 231 then 'timestamp(9) with local time zone' - when 182 then 'interval year(9) to month' - when 183 then 'interval day(9) to second(9)' - when 112 then case when l_national then 'nclob' else 'clob' end - when 113 then 'blob' - when 23 then 'raw(32767)' - when 109 then '"' || a_column.col_schema_name || '"."' || a_column.col_type_name || '"' - when 252 then 'boolean' - end; - end; - - -- the value as ANYDATA; BOOLEAN has no ANYDATA representation, so it travels as 1 or 0 - function value_expression(a_column dbms_sql.desc_rec3, a_variable varchar2) return varchar2 is - l_national boolean := a_column.col_charsetform = 2; - begin - return 'sys.anydata.' || - case a_column.col_type - when 1 then case when l_national then 'convertnvarchar2' else 'convertvarchar2' end - when 96 then case when l_national then 'convertnvarchar2' else 'convertvarchar2' end - when 2 then 'convertnumber' - when 100 then 'convertbfloat' - when 101 then 'convertbdouble' - when 12 then 'convertdate' - when 180 then 'converttimestamp' - when 181 then 'converttimestamptz' - when 231 then 'converttimestampltz' - when 182 then 'convertintervalym' - when 183 then 'convertintervalds' - when 112 then case when l_national then 'convertnclob' else 'convertclob' end - when 113 then 'convertblob' - when 23 then 'convertraw' - when 109 then case when is_collection(a_column) then 'convertcollection' else 'convertobject' end - when 252 then 'convertnumber' - end || - case when a_column.col_type = 252 - then '(case when ' || a_variable || ' then 1 when not ' || a_variable || ' then 0 end)' - else '(' || a_variable || ')' - end; - end; - - -- the argument passed to the test procedure; ut_executable declares l_ut_value_ for object types and collections - function argument_expression(a_column dbms_sql.desc_rec3, a_position integer) return varchar2 is - l_value varchar2(200 char) := 'l_ut_values(' || a_position || ')'; - l_national boolean := a_column.col_charsetform = 2; - begin - return - case a_column.col_type - when 1 then l_value || case when l_national then '.accessnvarchar2()' else '.accessvarchar2()' end - when 96 then l_value || case when l_national then '.accessnvarchar2()' else '.accessvarchar2()' end - when 2 then l_value || '.accessnumber()' - when 100 then l_value || '.accessbfloat()' - when 101 then l_value || '.accessbdouble()' - when 12 then l_value || '.accessdate()' - when 180 then l_value || '.accesstimestamp()' - when 181 then l_value || '.accesstimestamptz()' - when 231 then l_value || '.accesstimestampltz()' - when 182 then l_value || '.accessintervalym()' - when 183 then l_value || '.accessintervalds()' - when 112 then l_value || case when l_national then '.accessnclob()' else '.accessclob()' end - when 113 then l_value || '.accessblob()' - when 23 then l_value || '.accessraw()' - when 109 then 'l_ut_value_' || a_position - when 252 then 'case ' || l_value || '.accessnumber() when 1 then true when 0 then false end' - end; - end; - - -- values are shown like in a JSON or PL/SQL test case: dates and times in ISO format, numbers with a leading zero - function display_expression(a_column dbms_sql.desc_rec3, a_variable varchar2) return varchar2 is - begin - return - case - when a_column.col_type = 12 then 'to_char(' || a_variable || ', ''yyyy-mm-dd"T"hh24:mi:ss'')' - when a_column.col_type = 180 then 'to_char(' || a_variable || ', ''yyyy-mm-dd"T"hh24:mi:ss.ff6'')' - when a_column.col_type = 181 then 'to_char(' || a_variable || ', ''yyyy-mm-dd"T"hh24:mi:ss.ff6tzh:tzm'')' - when a_column.col_type = 231 then - 'to_char(cast(' || a_variable || ' as timestamp with time zone), ''yyyy-mm-dd"T"hh24:mi:ss.ff6tzh:tzm'')' - when a_column.col_type in (2, 100, 101) then - 'regexp_replace(to_char(' || a_variable || ', ''TM9'', ''nls_numeric_characters=''''.,''''''), ''^(-?)\.'', ''\10.'')' - when a_column.col_type in (1, 96, 182, 183) then 'to_char(' || a_variable || ')' - when a_column.col_type = 112 then 'dbms_lob.substr(' || a_variable || ', 100)' - when a_column.col_type = 23 then 'rawtohex(' || a_variable || ')' - when a_column.col_type = 252 then 'case when ' || a_variable || ' then ''true'' when not ' || a_variable || ' then ''false'' end' - else '''<' || nvl(a_column.col_type_name, 'value') || '>''' - end; - end; - begin - l_index := l_parameters.first; - while l_index is not null loop - if l_parameters(l_index).overload != l_parameters(l_parameters.first).overload then - raise_invalid('can''t be used with the overloaded procedure ' || upper(self.item.procedure_name)); - end if; - if l_parameters(l_index).parameter_name is not null then - l_params.extend; - l_params(l_params.last) := l_parameters(l_index); - end if; - l_index := l_parameters.next(l_index); - end loop; - execute immediate - 'declare l_ut_rc sys_refcursor; begin l_ut_rc := ' || l_function_call || '; :ut_cursor := dbms_sql.to_cursor_number(l_ut_rc); end;' - using out l_cursor; - begin - dbms_sql.describe_columns3(l_cursor, l_count, l_columns); - for i in 1 .. l_count loop - if argument_expression(l_columns(i), i) is null - or l_columns(i).col_type = 109 and l_columns(i).col_schema_name = 'SYS' then - raise_invalid( - 'returned column ' || l_columns(i).col_name || ', which has a data type that can''t be passed to the test: ' - || nvl(l_columns(i).col_type_name, to_char(l_columns(i).col_type)) - ); - end if; - l_param_of(i) := find_parameter(l_columns(i).col_name); - if l_param_of(i) > 0 then - if l_column_of.exists(l_param_of(i)) then - raise_invalid( - 'returned columns ' || l_columns(l_column_of(l_param_of(i))).col_name || ' and ' || l_columns(i).col_name - || ' for the same parameter ' || l_params(l_param_of(i)).parameter_name - ); - end if; - l_column_of(l_param_of(i)) := i; - end if; - end loop; - -- columns named like parameters are passed by name; when none is, all columns are passed by position - l_named := l_column_of.count > 0; - if not l_named then - if l_count != l_params.count then - raise_invalid( - 'returned ' || l_count || ' column(s) and none is named like a parameter, but the test procedure has ' - || l_params.count || ' parameter(s); name the columns like the parameters or return one column per parameter' - ); - end if; - for i in 1 .. l_count loop - l_param_of(i) := i; - l_column_of(i) := i; - end loop; - end if; - -- a column that is neither passed nor shown is an error, so that a misspelled column name - -- doesn't silently leave its parameter at the default, like a misspelled JSON key - for i in 1 .. l_count loop - if l_param_of(i) = 0 and not is_in_description(l_columns(i).col_name, i) then - raise_invalid( - 'returned column ' || l_columns(i).col_name || ', which is no parameter of the test procedure and isn''t used in the description' - ); - elsif l_param_of(i) > 0 and not fits(l_columns(i), l_params(l_param_of(i))) then - raise_invalid( - 'returned column ' || l_columns(i).col_name || ' of type ' || upper(regexp_replace(declaration(l_columns(i)), '\([0-9]+\)')) - || ', which can''t be passed to parameter ' || l_params(l_param_of(i)).parameter_name - || ' of type ' || parameter_type(l_params(l_param_of(i))) - ); - end if; - end loop; - l_index := l_params.first; - while l_index is not null loop - if l_params(l_index).defaulted = 'N' and not l_column_of.exists(l_index) then - raise_invalid('returned no column for parameter ' || l_params(l_index).parameter_name || ', which has no default value'); - end if; - l_index := l_params.next(l_index); - end loop; - for i in 1 .. l_count loop - if l_param_of(i) > 0 then - l_argument := case when l_arguments is not null then ', ' end - || case when l_named then '"' || l_params(l_param_of(i)).parameter_name || '" => ' end - || argument_expression(l_columns(i), i); - if nvl(lengthc(l_arguments), 0) + lengthc(l_argument) > ut_utils.gc_max_storage_varchar2_len then - raise_invalid('returned more columns than can be passed to the test procedure'); - end if; - l_arguments := l_arguments || l_argument; - end if; - l_declarations := l_declarations || ' l_ut_v' || i || ' ' || declaration(l_columns(i)) || ';' || chr(10); - l_defines := l_defines || ' dbms_sql.' || - case - when l_columns(i).col_type = 23 then 'define_column_raw(l_ut_c, ' || i || ', l_ut_v' || i || ', 32767);' - when l_columns(i).col_type in (1, 96) then 'define_column(l_ut_c, ' || i || ', l_ut_v' || i || ', 32767);' - else 'define_column(l_ut_c, ' || i || ', l_ut_v' || i || ');' - end || chr(10); - l_fetches := l_fetches || ' dbms_sql.column_value' || case when l_columns(i).col_type = 23 then '_raw' end - || '(l_ut_c, ' || i || ', l_ut_v' || i || ');' || chr(10); - l_values_code := l_values_code || - ' l_ut_values(l_ut_values.count - ' || (l_count - i) || ') := ' || value_expression(l_columns(i), 'l_ut_v' || i) || ';' || chr(10); - l_display_code := l_display_code || - ' l_ut_display(l_ut_display.count - ' || (l_count - i) || ') := substr(' || display_expression(l_columns(i), 'l_ut_v' || i) - || ', 1, ' || ut_utils.gc_max_storage_varchar2_len || ');' || chr(10); - l_names.extend; - l_names(i) := l_columns(i).col_name; - end loop; - - execute immediate - 'declare' || chr(10) || - ' l_ut_c integer := :ut_cursor;' || chr(10) || - ' l_ut_values ' || ut_utils.ut_owner || '.ut_anydata_list := ' || ut_utils.ut_owner || '.ut_anydata_list();' || chr(10) || - ' l_ut_display ' || ut_utils.ut_owner || '.ut_varchar2_list := ' || ut_utils.ut_owner || '.ut_varchar2_list();' || chr(10) || - l_declarations || - 'begin' || chr(10) || - l_defines || - ' while dbms_sql.fetch_rows(l_ut_c) > 0 loop' || chr(10) || - l_fetches || - ' l_ut_values.extend(' || l_count || ');' || chr(10) || - ' l_ut_display.extend(' || l_count || ');' || chr(10) || - l_values_code || - l_display_code || - ' end loop;' || chr(10) || - ' dbms_sql.close_cursor(l_ut_c);' || chr(10) || - ' :ut_values := l_ut_values;' || chr(10) || - ' :ut_display := l_ut_display;' || chr(10) || - 'end;' - using in l_cursor, out l_values, out l_display; - exception - when others then - if dbms_sql.is_open(l_cursor) then - dbms_sql.close_cursor(l_cursor); - end if; - raise; - end; - - for l_row_no in 1 .. l_values.count / l_count loop - l_row_values := ut_anydata_list(); - l_row_display := ut_varchar2_list(); - for i in 1 .. l_count loop - l_row_values.extend; - l_row_values(i) := l_values((l_row_no - 1) * l_count + i); - l_row_display.extend; - l_row_display(i) := nvl(l_display((l_row_no - 1) * l_count + i), 'null'); - end loop; - ut_test_case_values.set_values( - add_test_case( - l_row_no, - ut_utils.get_test_case_description(self.description, l_names, l_row_display), - l_arguments - ), - l_row_values - ); - end loop; - end; begin case l_parts.count when 1 then @@ -594,20 +219,44 @@ create or replace noneditionable type body ut_test as dbms_assert.enquote_name(l_owner, false) || '.' || dbms_assert.enquote_name(l_package, false) || '.' || dbms_assert.enquote_name(l_function, false) || '()'; l_return_type := ut_metadata.get_function_return_type(l_owner, l_package, l_function); - case - when l_return_type.data_type = 'REF CURSOR' then - add_cursor_test_cases(); - -- json_array_t rather than text, so that what the function returns is a JSON array (decided in #1326) - when l_return_type.data_type = 'OBJECT' and l_return_type.type_name = 'JSON_ARRAY_T' then - add_json_test_cases(); - when l_return_type.data_type is null then - raise_invalid('doesn''t exist or can''t be called without arguments'); - else - raise_invalid( - 'must return json_array_t or sys_refcursor, not ' - || nvl(l_return_type.type_name, l_return_type.data_type) - ); - end case; + if l_return_type.data_type is null then + raise_invalid('doesn''t exist or can''t be called without arguments'); + elsif not (l_return_type.data_type = 'OBJECT' and l_return_type.type_name = 'JSON_ARRAY_T') then + -- json_array_t rather than text or a cursor, so that what the function returns is a JSON array (#1326) + raise_invalid('must return json_array_t, not ' || nvl(l_return_type.type_name, l_return_type.data_type)); + end if; + + execute immediate + 'declare l_ut_cases json_array_t := ' || l_function_call || ';' || + ' begin if l_ut_cases is not null then :ut_json := l_ut_cases.to_clob(); else :ut_json := null; end if; end;' + using out l_json; + -- a function that returns null has no test cases + if l_json is null then + return l_result; + end if; + + l_parameters := + ut_metadata.get_package_parameters(upper(self.item.owner_name), upper(self.item.object_name), upper(self.item.procedure_name)); + for i in 1 .. l_parameters.count loop + if l_parameters(i).overload = l_parameters(1).overload and l_parameters(i).parameter_name is not null then + l_names.extend; + l_names(l_names.last) := l_parameters(i).parameter_name; + end if; + end loop; + -- each element is a test case, also one that is no JSON array or object: it errors when it runs; + -- its JSON text is converted to the parameter types when the test case runs + l_array := json_array_t.parse(l_json); + for i in 0 .. l_array.get_size - 1 loop + l_json := l_array.get(i).to_clob; + l_test := self; + l_test.name := self.name || '[' || (i + 1) || ']'; + l_test.path := self.path || '[' || (i + 1) || ']'; + l_test.description := ut_test_case_json.get_test_case_description(self.description, l_json, l_names); + l_test.item.call_source_row := i + 1; + ut_test_case_values.set_json(l_test.path, l_json); + l_result.extend; + l_result(l_result.last) := l_test; + end loop; return l_result; end; end; diff --git a/source/core/types/ut_test.tps b/source/core/types/ut_test.tps index 594fc386e..9c372d3da 100644 --- a/source/core/types/ut_test.tps +++ b/source/core/types/ut_test.tps @@ -68,7 +68,7 @@ create or replace noneditionable type ut_test force under ut_suite_item ( member function get_failed_expectation_lines return ut_varchar2_rows, overriding member function has_test_case_source(self in ut_test) return boolean, /** - * Calls the --%testcasesource function and returns one test for each element of its JSON array or row of its cursor. + * Calls the --%testcasesource function and returns one test for each element of its JSON array. */ member function get_source_test_cases(self in ut_test) return ut_suite_items ) diff --git a/source/core/ut_suite_builder.pkb b/source/core/ut_suite_builder.pkb index f8ec76be8..04137efb1 100644 --- a/source/core/ut_suite_builder.pkb +++ b/source/core/ut_suite_builder.pkb @@ -377,82 +377,6 @@ create or replace noneditionable package body ut_suite_builder is return l_result; end; - /* - Checks the arguments of a JSON test case (see ut_test_case_json.get_argument_names) against the parameters of the procedure: - number of values, parameter names and parameters without default value. - Types are not checked here; values are converted when the test case runs. - Returns null when the arguments fit one of the overloads, or when the procedure is not known (it is reported when called). - */ - function get_arguments_error( - a_annotations t_annotations_info, - a_procedure_name t_object_name, - a_argument_names ut_varchar2_list - ) return varchar2 is - l_procedure_name t_object_name := upper(a_procedure_name); - l_overload varchar2(40 char); - l_names ut_varchar2_list := ut_varchar2_list(); - l_defaulted ut_varchar2_list := ut_varchar2_list(); - l_error varchar2(4000 char); - l_first_error varchar2(4000 char); - - function get_overload_error return varchar2 is - type tt_given is table of boolean index by t_object_name; - l_given tt_given; - l_name t_object_name; - l_missing varchar2(4000 char); - begin - for i in 1 .. a_argument_names.count loop - l_name := upper(a_argument_names(i)); - if l_name is null then - if i > l_names.count then - return a_argument_names.count || ' value(s) given, but the procedure has ' || l_names.count || ' parameter(s)'; - end if; - l_given(l_names(i)) := true; - else - if not l_name member of l_names then - return 'the procedure has no parameter ' || l_name; - elsif l_given.exists(l_name) then - return 'parameter ' || l_name || ' is given twice'; - end if; - l_given(l_name) := true; - end if; - end loop; - for i in 1 .. l_names.count loop - if l_defaulted(i) = 'N' and not l_given.exists(l_names(i)) then - l_missing := l_missing || case when l_missing is not null then ', ' end || l_names(i); - end if; - end loop; - return case when l_missing is not null then 'no value for parameter(s) ' || l_missing end; - end; - begin - for i in 1 .. a_annotations.parameters.count loop - if a_annotations.parameters(i).procedure_name = l_procedure_name then - if l_overload is not null and l_overload != a_annotations.parameters(i).overload then - l_error := get_overload_error(); - if l_error is null then - return null; - end if; - l_first_error := coalesce(l_first_error, l_error); - l_names := ut_varchar2_list(); - l_defaulted := ut_varchar2_list(); - end if; - l_overload := a_annotations.parameters(i).overload; - -- an overload without parameters has one entry without parameter name - if a_annotations.parameters(i).parameter_name is not null then - l_names.extend; - l_names(l_names.last) := a_annotations.parameters(i).parameter_name; - l_defaulted.extend; - l_defaulted(l_defaulted.last) := a_annotations.parameters(i).defaulted; - end if; - end if; - end loop; - if l_overload is not null then - l_error := get_overload_error(); - return case when l_error is not null then coalesce(l_first_error, l_error) end; - end if; - return null; - end; - procedure add_test_cases( a_suite in out nocopy ut_suite, a_suite_items in out nocopy ut_suite_items, @@ -463,23 +387,19 @@ create or replace noneditionable package body ut_suite_builder is l_test ut_test; l_position t_annotation_position := a_test_cases.first; l_case_no binary_integer := 0; - l_error varchar2(4000 char); l_arguments varchar2(4000 char); l_parameters ut_metadata.tt_parameters := get_parameters(a_annotations, a_test.name); begin while l_position is not null loop - -- cases are numbered by annotation, so that the number of a case does not change when another case is invalid + -- cases are numbered by annotation, so that the number of a case doesn't change when an empty annotation is filled l_case_no := l_case_no + 1; l_arguments := trim(a_test_cases(l_position)); - l_error := ut_test_case_json.get_json_error(l_arguments); - if l_error is null then - l_error := get_arguments_error(a_annotations, a_test.name, ut_test_case_json.get_argument_names(l_arguments)); - end if; - if l_error is not null then + if l_arguments is null then add_annotation_ignored_warning( - a_suite, gc_testcase, 'Annotation %%% has invalid arguments: ' || l_error || '.', l_position, a_test.name + a_suite, gc_testcase, 'Annotation %%% requires a JSON array or object, e.g. "--%testcase([1, 2])".', l_position, a_test.name ); else + -- each test case is a test, also an invalid one: it errors when it runs (see ut_test_case_json.get_call) l_test := a_test; -- each case gets its own cache row, keyed by owner + path and by owner + package + line l_test.line_no := l_position; diff --git a/source/core/ut_suite_cache_macros.pkb b/source/core/ut_suite_cache_macros.pkb index a39ebbf30..a9fa5771e 100644 --- a/source/core/ut_suite_cache_macros.pkb +++ b/source/core/ut_suite_cache_macros.pkb @@ -18,9 +18,16 @@ create or replace noneditionable package body ut_suite_cache_macros as function match_paths(a_items dbms_tf.table_t, a_paths dbms_tf.table_t) return varchar2 sql_macro is begin - --names: "_" is not a wildcard, "*" is; suitepath patterns: "." and "$" are literal, "*" matches part of a path element - return q'[ - select p.path_id, i.object_owner, i.path + --names: "_" is not a wildcard, "*" is; suitepath patterns: ".", "$", "[" and "]" are literal, "*" matches part of a path element + --a test with a --%testcasesource has one row for all its test cases, which are known only when it runs: + --"procedure[n]" selects that row, and test_case_no tells which of its test cases to run + --q'~ quoting, as the text contains ]' + return q'~ + select p.path_id, i.object_owner, i.path, + case + when i.has_test_case_source = 'Y' and coalesce(p.procedure_name, p.suite_path) like '%]' then + to_number(regexp_substr(coalesce(p.procedure_name, p.suite_path), '\[([0-9]+)\]$', 1, 1, null, 1)) + end as test_case_no from a_items i join a_paths p on i.object_owner = upper(p.schema_name) @@ -30,17 +37,20 @@ create or replace noneditionable package body ut_suite_cache_macros as and ( p.procedure_name is null or p.procedure_name = '*' or i.name like replace(replace(upper(p.procedure_name), '_', '\_'), '*', '%') escape '\' or i.name like replace(replace(upper(p.procedure_name), '_', '\_'), '*', '%') || '[%' escape '\' + or ( i.has_test_case_source = 'Y' and i.name = regexp_replace(upper(p.procedure_name), '\[[0-9]+\]$') ) ) ) or ( instr(p.suite_path, '*') = 0 - and ( i.path = p.suite_path or substr(i.path, 1, length(p.suite_path) + 1) in (p.suite_path || '.', p.suite_path || '[') ) + and ( i.path = p.suite_path or substr(i.path, 1, length(p.suite_path) + 1) in (p.suite_path || '.', p.suite_path || '[') + or ( i.has_test_case_source = 'Y' and i.path = regexp_replace(p.suite_path, '\[[0-9]+\]$') ) + ) ) or ( instr(p.suite_path, '*') > 0 and regexp_like( i.path, - '^' || replace(replace(replace(p.suite_path, '.', '\.'), '$', '\$'), '*', '[[:alnum:]$#_]*') + '^' || replace(replace(replace(replace(replace(p.suite_path, '.', '\.'), '$', '\$'), '[', '\['), ']', '\]'), '*', '[[:alnum:]$#_]*') ) - )]'; + )~'; end; end; diff --git a/source/core/ut_suite_cache_macros.pks b/source/core/ut_suite_cache_macros.pks index 2554ccba2..cd53a4ecd 100644 --- a/source/core/ut_suite_cache_macros.pks +++ b/source/core/ut_suite_cache_macros.pks @@ -26,15 +26,19 @@ create or replace noneditionable package ut_suite_cache_macros authid definer as /** * Table SQL macro matching suite items with run paths: the single definition of which items a run path selects. - * Returns one row (path_id, object_owner, path) for every pair of a path and an item it selects: + * Returns one row (path_id, object_owner, path, test_case_no) for every pair of a path and an item it selects: * - schema: all items of the schema * - schema.package[.*]: all items of the package - * - schema.package.procedure: the items named like the procedure + * - schema.package.procedure: the items named like the procedure, and its test cases (procedure[n]) + * - schema.package.procedure[n]: test case n of the procedure * - schema:suite.path: the item at the suitepath and all items below it * - schema:suite*.path: the items whose path starts with a match of the suitepath pattern * Package and procedure names may contain wildcards (*). Parents of the selected items are not returned. + * A test with a --%testcasesource has a single item for its test cases: a path ending in [n] selects it, + * with test_case_no n; test_case_no is null for all other pairs. * - * @param a_items table or query with columns object_owner, object_name, name, path (as in ut_suite_cache), without collection columns + * @param a_items table or query with columns object_owner, object_name, name, path (as in ut_suite_cache) + * and has_test_case_source ('Y' for a test with a --%testcasesource), without collection columns * @param a_paths table or query with columns path_id and the columns of ut_path_item */ function match_paths(a_items dbms_tf.table_t, a_paths dbms_tf.table_t) return varchar2 sql_macro; diff --git a/source/core/ut_suite_cache_manager.pkb b/source/core/ut_suite_cache_manager.pkb index 87c58f307..ad7466384 100644 --- a/source/core/ut_suite_cache_manager.pkb +++ b/source/core/ut_suite_cache_manager.pkb @@ -65,7 +65,8 @@ create or replace noneditionable package body ut_suite_cache_manager is ), schema_items as ( --only scalar columns: a table argument of a SQL macro cannot have collection columns (ORA-62558) - select /*+ no_parallel */ c.id, c.object_owner, c.object_name, c.name, c.path + select /*+ no_parallel */ c.id, c.object_owner, c.object_name, c.name, c.path, + case when c.item.call_source is not null then 'Y' end as has_test_case_source from &&ut3_owner..ut_suite_cache c where c.object_owner in (select upper(p.schema_name) from path_items p) ) @@ -85,6 +86,35 @@ create or replace noneditionable package body ut_suite_cache_manager is return l_results; end; + function get_test_case_filters( + a_schema_paths ut_path_items + ) return ut_key_value_pairs is + l_results ut_key_value_pairs; + begin + with + path_items as ( + select rownum as path_id, sp.schema_name, sp.object_name, sp.procedure_name, sp.suite_path + from table(a_schema_paths) sp + ), + schema_items as ( + select /*+ no_parallel */ c.object_owner, c.object_name, c.name, c.path, + case when c.item.call_source is not null then 'Y' end as has_test_case_source + from &&ut3_owner..ut_suite_cache c + where c.object_owner in (select upper(p.schema_name) from path_items p) + and c.item.call_source is not null + ) + --the selected test case numbers of the tests that no path selects as a whole + select /*+ no_parallel */ &&ut3_owner..ut_key_value_pair(f.object_owner || ':' || f.path, to_char(f.test_case_no)) + bulk collect into l_results + from ( + select distinct m.object_owner, m.path, m.test_case_no, + count(case when m.test_case_no is null then 1 end) over (partition by m.object_owner, m.path) as whole_test_paths + from (&&ut3_owner..ut_suite_cache_macros.match_paths(schema_items, path_items)) m + ) f + where f.whole_test_paths = 0; + return l_results; + end; + /* Returns suite items for the paths, sorted bottom up, so that reconstruct_from_cache in ut_suite_manager can build the suite hierarchy in a single pass. The statement: diff --git a/source/core/ut_suite_cache_manager.pks b/source/core/ut_suite_cache_manager.pks index 1ff9552cc..6acd0c92a 100644 --- a/source/core/ut_suite_cache_manager.pks +++ b/source/core/ut_suite_cache_manager.pks @@ -65,6 +65,16 @@ create or replace noneditionable package ut_suite_cache_manager authid current_u a_random_seed positive := null ) return ut_suite_cache_rows; + /* + * The test cases that the paths select from tests with a --%testcasesource, e.g. "pkg.test[2]": + * key = owner || ':' || path of the test, value = number of the test case. + * A test that a path selects as a whole (e.g. "pkg.test" or "pkg") has no entry, so all its test cases run. + * Not to be used publicly. Used internally for building suites at runtime. + */ + function get_test_case_filters( + a_schema_paths ut_path_items + ) return ut_key_value_pairs; + /* * Retrieves information about the suite items matching the paths, as get_suite_rows does without tags. * Not to be used publicly. Used internally for ut_runner.get_suites_info. diff --git a/source/core/ut_suite_manager.pkb b/source/core/ut_suite_manager.pkb index e2eee4288..f1f844f0e 100644 --- a/source/core/ut_suite_manager.pkb +++ b/source/core/ut_suite_manager.pkb @@ -300,7 +300,8 @@ create or replace noneditionable package body ut_suite_manager is from table(a_schema_paths) sp ), suite_items as ( - select r.object_owner, r.object_name, r.name, r.path + select r.object_owner, r.object_name, r.name, r.path, + case when r.item.call_source is not null then 'Y' end as has_test_case_source from table(a_suite_rows) r ) select /*+ no_parallel */ p.schema_name, p.object_name, p.procedure_name, p.suite_path @@ -503,7 +504,8 @@ create or replace noneditionable package body ut_suite_manager is a_random_seed positive := null, a_tags varchar2 := null ) is - l_tags_match integer; + l_tags_match integer; + l_schema_paths ut_path_items; begin ut_event_manager.trigger_event('configure_execution_by_path - start'); --raise an error for an invalid tag expression even when the paths select no tests to evaluate it on @@ -511,13 +513,15 @@ create or replace noneditionable package body ut_suite_manager is l_tags_match := ut_suite_tag_filter.is_matching(null, a_tags); end if; a_suites := ut_suite_items(); + l_schema_paths := refresh_cache_for_paths(a_paths); add_suites_for_paths( - refresh_cache_for_paths(a_paths), + l_schema_paths, a_suites, a_random_seed, a_tags ); + ut_test_case_values.set_case_filters(ut_suite_cache_manager.get_test_case_filters(l_schema_paths)); ut_event_manager.trigger_event('configure_execution_by_path - end'); end configure_execution_by_path; diff --git a/source/core/ut_test_case_json.pkb b/source/core/ut_test_case_json.pkb index 086d1a4a5..ddbe52053 100644 --- a/source/core/ut_test_case_json.pkb +++ b/source/core/ut_test_case_json.pkb @@ -66,7 +66,7 @@ create or replace noneditionable package body ut_test_case_json as a_values.extend; a_values(a_values.last) := display_value(l_array.get(i), case when l_array.get(i).is_string then l_array.get_clob(i) end); end loop; - else + elsif l_element.is_object then l_object := treat(l_element as json_object_t); l_keys := l_object.get_keys; for i in 1 .. l_keys.count loop @@ -77,17 +77,14 @@ create or replace noneditionable package body ut_test_case_json as l_object.get(l_keys(i)), case when l_object.get(l_keys(i)).is_string then l_object.get_clob(l_keys(i)) end ); end loop; + else + -- a test case that is no JSON array or object errors when it runs, but is shown with its value + a_names.extend; + a_values.extend; + a_values(1) := dbms_lob.substr(l_element.to_clob, ut_utils.gc_max_storage_varchar2_len); end if; end; - function get_argument_names(a_json clob) return ut_varchar2_list is - l_names ut_varchar2_list; - l_values ut_varchar2_list; - begin - get_names_and_values(a_json, l_names, l_values); - return l_names; - end; - function get_test_case_description( a_description varchar2, a_json clob, a_parameter_names ut_varchar2_list := null ) return varchar2 is @@ -96,6 +93,12 @@ create or replace noneditionable package body ut_test_case_json as begin get_names_and_values(a_json, l_names, l_values, a_parameter_names); return ut_utils.get_test_case_description(a_description, l_names, l_values); + exception + when others then + -- text that is no JSON is shown as it is; the test case errors when it runs + return ut_utils.get_test_case_description( + a_description, ut_varchar2_list(null), ut_varchar2_list(dbms_lob.substr(a_json, ut_utils.gc_max_storage_varchar2_len)) + ); end; function get_call(a_owner varchar2, a_package varchar2, a_procedure varchar2, a_call_name varchar2, a_json clob) return varchar2 is @@ -103,7 +106,7 @@ create or replace noneditionable package body ut_test_case_json as l_all_parameters ut_metadata.tt_parameters := ut_metadata.get_package_parameters(upper(a_owner), upper(a_package), upper(a_procedure)); l_parameters ut_metadata.tt_parameters := ut_metadata.tt_parameters(); - l_element json_element_t := json_element_t.parse(a_json); + l_element json_element_t; l_array json_array_t; l_keys json_key_list; l_case_type varchar2(30 char); @@ -254,22 +257,22 @@ create or replace noneditionable package body ut_test_case_json as l_arguments := l_arguments || case when l_arguments is not null then ', ' end || '"' || a_parameter.parameter_name || '" => ' || l_variable; end; - -- a key that is no parameter is an error, not ignored, so that a misspelled key doesn't silently leave - -- a parameter at its default (decided in #1326) + -- the parameter named like a key, not case-sensitive; null for a key that is no parameter function find_parameter(a_key varchar2) return ut_metadata.t_parameter is l_result ut_metadata.t_parameter; begin for i in 1 .. l_parameters.count loop - if l_parameters(i).parameter_name = upper(a_key) then + if upper(l_parameters(i).parameter_name) = upper(a_key) then l_result := l_parameters(i); end if; end loop; - if l_result.parameter_name is null then - raise_invalid('the procedure has no parameter ' || a_key); - end if; return l_result; end; begin + if get_json_error(a_json) is not null then + raise_invalid(get_json_error(a_json)); + end if; + l_element := json_element_t.parse(a_json); for i in 1 .. l_all_parameters.count loop if l_all_parameters(i).overload != l_all_parameters(1).overload then raise_invalid('JSON test cases can''t be used with the overloaded procedure ' || upper(a_procedure)); @@ -279,35 +282,37 @@ create or replace noneditionable package body ut_test_case_json as l_parameters(l_parameters.last) := l_all_parameters(i); end if; end loop; + if l_parameters.count = 0 then + raise_invalid('the procedure ' || upper(a_procedure) || ' has no parameters, so it can''t be run with test cases'); + end if; + -- values and keys beyond the parameters are ignored (see the package specification); + -- the generated code never contains a key, it reads the values by position if l_element.is_array then l_case_type := 'json_array_t'; l_array := treat(l_element as json_array_t); - if l_array.get_size > l_parameters.count then - raise_invalid(l_array.get_size || ' value(s) given, but the procedure has ' || l_parameters.count || ' parameter(s)'); - end if; - for i in 0 .. l_array.get_size - 1 loop + for i in 0 .. least(l_array.get_size, l_parameters.count) - 1 loop add_argument(l_parameters(i + 1), to_char(i)); l_given.extend; - l_given(l_given.last) := l_parameters(i + 1).parameter_name; + l_given(l_given.last) := upper(l_parameters(i + 1).parameter_name); end loop; else - -- only JSON arrays and objects get here, see get_json_error and ut_test.get_source_test_cases l_case_type := 'json_object_t'; l_keys := treat(l_element as json_object_t).get_keys; for i in 1 .. l_keys.count loop - if upper(l_keys(i)) member of l_given then - raise_invalid('parameter ' || upper(l_keys(i)) || ' is given twice'); + if find_parameter(l_keys(i)).parameter_name is not null then + if upper(l_keys(i)) member of l_given then + raise_invalid('parameter ' || upper(l_keys(i)) || ' is given twice'); + end if; + l_given.extend; + l_given(l_given.last) := upper(l_keys(i)); + add_argument(find_parameter(l_keys(i)), 'l_ut_keys(' || i || ')'); end if; - l_given.extend; - l_given(l_given.last) := upper(l_keys(i)); - -- the key matches a parameter name, so it can be used in a string literal as it is - add_argument(find_parameter(l_keys(i)), '''' || l_keys(i) || ''''); end loop; end if; l_index := l_parameters.first; while l_index is not null loop - if l_parameters(l_index).defaulted = 'N' and not l_parameters(l_index).parameter_name member of l_given then + if l_parameters(l_index).defaulted = 'N' and not upper(l_parameters(l_index).parameter_name) member of l_given then raise_invalid('no value for parameter ' || l_parameters(l_index).parameter_name || ', which has no default value'); end if; l_index := l_parameters.next(l_index); @@ -316,6 +321,7 @@ create or replace noneditionable package body ut_test_case_json as return 'declare' || chr(10) || ' l_ut_case ' || l_case_type || ' := ' || l_case_type || '.parse(:ut_json);' || chr(10) || + case when l_case_type = 'json_object_t' then ' l_ut_keys json_key_list := l_ut_case.get_keys;' || chr(10) end || l_declarations || l_functions || 'begin' || chr(10) || diff --git a/source/core/ut_test_case_json.pks b/source/core/ut_test_case_json.pks index 84626818e..15c96e6d2 100644 --- a/source/core/ut_test_case_json.pks +++ b/source/core/ut_test_case_json.pks @@ -19,28 +19,22 @@ create or replace noneditionable package ut_test_case_json authid current_user a /** * Test cases given as JSON, by --%testcase or by a --%testcasesource function: * a JSON array passes its values by position, a JSON object passes its values to the parameters named like its keys. + * Values and keys beyond the parameters are ignored, so that one source of test cases can serve several tests + * and the description can show values that aren't passed (#1326). */ - /** - * Returns the reason why a text can't be the arguments of a test case (a JSON array or object), or null when it can. - */ - function get_json_error(a_json clob) return varchar2; - - /** - * Returns the keys of a JSON object, or for a JSON array one null per value (passed by position), - * so that a test case can be checked against the parameters of the procedure (see ut_suite_builder). - */ - function get_argument_names(a_json clob) return ut_varchar2_list; - /** * Returns the description of a JSON test case, with the values of the test case filled in (see ut_utils.get_test_case_description). * Values of a JSON array can be referred to by the names of the parameters they are passed to, given in a_parameter_names. + * Text that is no JSON is appended to the description as it is. */ function get_test_case_description(a_description varchar2, a_json clob, a_parameter_names ut_varchar2_list := null) return varchar2; /** * Returns a PL/SQL block that calls the procedure with the values of a JSON test case, converted to the types of its parameters. * The block expects the JSON text as bind variable :ut_json. + * Raises ut_utils.gc_invalid_test_case_source when the test case can't be passed to the procedure, e.g. when it is no + * JSON array or object, a parameter without default value gets no value, or the procedure has no parameters. */ function get_call(a_owner varchar2, a_package varchar2, a_procedure varchar2, a_call_name varchar2, a_json clob) return varchar2; diff --git a/source/core/ut_test_case_values.pkb b/source/core/ut_test_case_values.pkb index 9592b0832..cfd4d2ace 100644 --- a/source/core/ut_test_case_values.pkb +++ b/source/core/ut_test_case_values.pkb @@ -16,35 +16,42 @@ create or replace noneditionable package body ut_test_case_values as limitations under the License. */ - type tt_values is table of ut_anydata_list index by varchar2(4000 char); type tt_json is table of clob index by varchar2(4000 char); - g_values tt_values; - g_json tt_json; + type tt_filters is table of ut_integer_list index by varchar2(4000 char); + g_json tt_json; + g_filters tt_filters; - procedure set_values(a_test_path varchar2, a_values ut_anydata_list) is + procedure set_json(a_test_path varchar2, a_json clob) is begin - g_values(a_test_path) := a_values; + g_json(a_test_path) := a_json; end; - function get_values(a_test_path varchar2) return ut_anydata_list is + function get_json(a_test_path varchar2) return clob is begin - return case when g_values.exists(a_test_path) then g_values(a_test_path) end; + return case when g_json.exists(a_test_path) then g_json(a_test_path) end; end; - procedure set_json(a_test_path varchar2, a_json clob) is + procedure remove_json(a_test_path varchar2) is begin - g_json(a_test_path) := a_json; + g_json.delete(a_test_path); end; - function get_json(a_test_path varchar2) return clob is + procedure set_case_filters(a_filters ut_key_value_pairs) is begin - return case when g_json.exists(a_test_path) then g_json(a_test_path) end; + g_filters.delete; + for i in 1 .. cardinality(a_filters) loop + if not g_filters.exists(a_filters(i).key) then + g_filters(a_filters(i).key) := ut_integer_list(); + end if; + g_filters(a_filters(i).key).extend; + g_filters(a_filters(i).key)(g_filters(a_filters(i).key).last) := to_number(a_filters(i).value); + end loop; end; - procedure remove_values(a_test_path varchar2) is + function get_case_filter(a_owner varchar2, a_test_path varchar2) return ut_integer_list is + l_key varchar2(4000 char) := upper(a_owner) || ':' || lower(a_test_path); begin - g_values.delete(a_test_path); - g_json.delete(a_test_path); + return case when g_filters.exists(l_key) then g_filters(l_key) else ut_integer_list() end; end; end; diff --git a/source/core/ut_test_case_values.pks b/source/core/ut_test_case_values.pks index b67e2ed83..3f008ed30 100644 --- a/source/core/ut_test_case_values.pks +++ b/source/core/ut_test_case_values.pks @@ -17,21 +17,28 @@ create or replace noneditionable package ut_test_case_values authid definer as */ /** - * Holds the argument values of --%testcasesource test cases from the moment a test is split into its - * test cases until each test case has run: the row values of a cursor as ANYDATA, or the JSON text of a JSON test case. - * The values can't be attributes of the suite item types, as those types are stored and queried with SQL, - * which doesn't allow ANYDATA in collections, and the JSON text can be longer than a varchar2 attribute. + * Holds the JSON text of the --%testcasesource test cases from the moment a test is split into its test cases + * until each test case has run. The JSON text can't be an attribute of the suite item types, as it can be longer + * than a varchar2 attribute. + * Also holds the test cases that a run selects by path, e.g. "pkg.test[2]", for tests with a --%testcasesource. */ - procedure set_values(a_test_path varchar2, a_values ut_anydata_list); - - function get_values(a_test_path varchar2) return ut_anydata_list; - procedure set_json(a_test_path varchar2, a_json clob); function get_json(a_test_path varchar2) return clob; - procedure remove_values(a_test_path varchar2); + procedure remove_json(a_test_path varchar2); + + /** + * Sets the test cases a run selects, replacing those of an earlier run. + * a_filters: key = owner || ':' || path of the test, value = number of a test case. + */ + procedure set_case_filters(a_filters ut_key_value_pairs); + + /** + * The numbers of the test cases selected for a test, empty when all its test cases run. + */ + function get_case_filter(a_owner varchar2, a_test_path varchar2) return ut_integer_list; end; / diff --git a/source/core/ut_utils.pkb b/source/core/ut_utils.pkb index 2e39bb3f6..77c7df68f 100644 --- a/source/core/ut_utils.pkb +++ b/source/core/ut_utils.pkb @@ -236,23 +236,50 @@ create or replace noneditionable package body ut_utils is a_description varchar2, a_names ut_varchar2_list, a_values ut_varchar2_list ) return varchar2 is c_max_value_length constant integer := 100; - l_result varchar2(32767) := a_description; - l_appendix varchar2(32767); - l_value varchar2(32767); + c_placeholder constant varchar2(30) := '\{([[:alnum:]_$#]+)\}'; + l_values ut_varchar2_list := ut_varchar2_list(); + l_result varchar2(32767); + l_appendix varchar2(32767); + l_position integer := 1; + l_start integer; + l_name varchar2(4000); + l_index integer; + l_unresolved boolean := false; + + -- the value a placeholder refers to: by number, or by name + function find_value(a_name varchar2) return integer is + begin + if regexp_like(a_name, '^[0-9]{1,9}$') and to_number(a_name) between 1 and l_values.count then + return to_number(a_name); + end if; + for i in 1 .. l_values.count loop + if upper(a_names(i)) = upper(a_name) then + return i; + end if; + end loop; + return null; + end; begin for i in 1 .. a_values.count loop -- long values would make the description unreadable - l_value := substr(a_values(i), 1, c_max_value_length) || case when length(a_values(i)) > c_max_value_length then '...' end; - l_appendix := l_appendix || case when i > 1 then ', ' end || l_value; - if regexp_like(a_description, '\{[[:alnum:]_$#]+\}') then - l_result := replace(l_result, '{' || i || '}', l_value); - if a_names(i) is not null then - l_result := replace(replace(l_result, '{' || a_names(i) || '}', l_value), '{' || lower(a_names(i)) || '}', l_value); - end if; - end if; + l_values.extend; + l_values(i) := substr(a_values(i), 1, c_max_value_length) || case when length(a_values(i)) > c_max_value_length then '...' end; + l_appendix := l_appendix || case when i > 1 then ', ' end || l_values(i); + end loop; + -- a single pass, so that a value that looks like a placeholder isn't replaced + loop + l_start := regexp_instr(a_description, c_placeholder, l_position); + exit when nvl(l_start, 0) = 0; + l_name := regexp_substr(a_description, c_placeholder, l_position, 1, null, 1); + l_index := find_value(l_name); + l_unresolved := l_unresolved or l_index is null; + l_result := l_result || substr(a_description, l_position, l_start - l_position) + || case when l_index is not null then l_values(l_index) else '{' || l_name || '}' end; + l_position := l_start + length(l_name) + 2; end loop; - if not regexp_like(a_description, '\{[[:alnum:]_$#]+\}') then - l_result := a_description || case when a_description is not null and l_appendix is not null then ' (' || l_appendix || ')' end; + l_result := l_result || substr(a_description, l_position); + if l_position = 1 or l_unresolved then + l_result := l_result || case when l_result is not null and l_appendix is not null then ' (' || l_appendix || ')' end; end if; return substrb(l_result, 1, gc_max_storage_varchar2_len); end; diff --git a/source/core/ut_utils.pks b/source/core/ut_utils.pks index 800404354..8c2329724 100644 --- a/source/core/ut_utils.pks +++ b/source/core/ut_utils.pks @@ -244,12 +244,13 @@ create or replace noneditionable package ut_utils authid definer is /** * * Builds the description of a test case of a --%testcase or --%testcasesource test. - * {1}, {2}, ... in the description are replaced with the values, {} with the value of that name. - * Without placeholders, the values separated by commas are appended in brackets. A null description stays null. + * {1}, {2}, ... in the description are replaced with the values, {} with the value of that name (not case-sensitive). + * When the description has no placeholder, or a placeholder that refers to no value, the values separated by commas + * are appended in brackets, so that the description always shows the values. A null description stays null. * Values longer than 100 characters are shortened. * * @param a_description the description of the test - * @param a_names names of the values (parameter or column names), elements may be null + * @param a_names names of the values (parameter names or JSON keys), elements may be null * @param a_values the values, as shown in the description */ function get_test_case_description( diff --git a/source/create_grants.sql b/source/create_grants.sql index 63e5a8ed0..5cf7cfaaa 100644 --- a/source/create_grants.sql +++ b/source/create_grants.sql @@ -73,7 +73,6 @@ grant execute on &&ut3_owner..ut_suite_cache_macros to &ut3_user; --generic types grant execute on &&ut3_owner..ut_varchar2_list to &ut3_user; grant execute on &&ut3_owner..ut_varchar2_rows to &ut3_user; -grant execute on &&ut3_owner..ut_anydata_list to &ut3_user; grant execute on &&ut3_owner..ut_integer_list to &ut3_user; grant execute on &&ut3_owner..ut_key_value_pairs to &ut3_user; grant execute on &&ut3_owner..ut_key_value_pair to &ut3_user; diff --git a/source/install.sql b/source/install.sql index 8f05490a2..81ac733b1 100644 --- a/source/install.sql +++ b/source/install.sql @@ -45,7 +45,6 @@ create or replace context &&ut3_owner._info using &&ut3_owner..ut_session_contex -- spec @@install_component.sql 'core/types/ut_varchar2_list.tps' @@install_component.sql 'core/types/ut_varchar2_rows.tps' -@@install_component.sql 'core/types/ut_anydata_list.tps' @@install_component.sql 'core/types/ut_integer_list.tps' @@install_component.sql 'core/types/ut_object_name.tps' @@install_component.sql 'core/types/ut_object_names.tps' diff --git a/source/uninstall_objects.sql b/source/uninstall_objects.sql index 95c200afb..c85dad777 100644 --- a/source/uninstall_objects.sql +++ b/source/uninstall_objects.sql @@ -404,8 +404,6 @@ drop type ut_varchar2_list force; drop type ut_varchar2_rows force; -drop type ut_anydata_list force; - drop package ut_coverage_profiler; drop package ut_compound_data_helper; diff --git a/test/ut3_tester/core/test_suite_builder.pkb b/test/ut3_tester/core/test_suite_builder.pkb index 71a4375c3..56f10c568 100644 --- a/test/ut3_tester/core/test_suite_builder.pkb +++ b/test/ut3_tester/core/test_suite_builder.pkb @@ -2012,7 +2012,7 @@ create or replace package body test_suite_builder is l_actual := invoke_builder_for_annotations(l_annotations, 'SOME_PACKAGE'); --Assert ut.expect(l_actual).to_be_like( - '%Amount 100, kind VIP, unknown {3}some_package.some_test[1]%' + '%Amount 100, kind VIP, unknown {3} (100, VIP)some_package.some_test[1]%' ); end; @@ -2088,9 +2088,6 @@ create or replace package body test_suite_builder is begin execute immediate q'[create or replace package test_case_args is procedure checked(a_amount number, a_half number); - procedure ovl(a number); - procedure ovl(a varchar2, b number); - procedure ovl; end;]'; end; @@ -2100,7 +2097,7 @@ create or replace package body test_suite_builder is execute immediate 'drop package test_case_args'; end; - procedure testcase_invalid_arguments is + procedure testcase_every_case_is_a_test is l_actual clob; l_annotations ut3_develop.ut_annotations; begin @@ -2111,26 +2108,28 @@ create or replace package body test_suite_builder is ut3_develop.ut_annotation(15, 'testcase', '[1, 2, 3]', 'checked'), ut3_develop.ut_annotation(16, 'testcase', '{"a_x": 1}', 'checked'), ut3_develop.ut_annotation(17, 'testcase', '{"a_half": 1}', 'checked'), - ut3_develop.ut_annotation(18, 'testcase', '{"a_amount": 1, "A_AMOUNT": 2, "a_half": 3}', 'checked'), - ut3_develop.ut_annotation(19, 'testcase', '1, 2', 'checked'), - ut3_develop.ut_annotation(20, 'testcase', 'a_amount => 1, a_half => 2', 'checked'), + ut3_develop.ut_annotation(18, 'testcase', '1, 2', 'checked'), + ut3_develop.ut_annotation(19, 'testcase', '[1, 2', 'checked'), + ut3_develop.ut_annotation(20, 'testcase', null, 'checked'), ut3_develop.ut_annotation(21, 'testcase', '{"a_half": 1000, "a_amount": 2000}', 'checked') ); --Act l_actual := invoke_builder_for_annotations(l_annotations, 'TEST_CASE_ARGS'); --Assert ut.expect(l_actual).to_be_like( - '%' || - '%has invalid arguments: 3 value(s) given, but the procedure has 2 parameter(s). Annotation ignored.' || - '%has invalid arguments: the procedure has no parameter A_X. Annotation ignored.' || - '%has invalid arguments: no value for parameter(s) A_AMOUNT. Annotation ignored.' || - '%has invalid arguments: parameter A_AMOUNT is given twice. Annotation ignored.' || - '%has invalid arguments: a JSON array or object is expected. Annotation ignored.' || - '%has invalid arguments: a JSON array or object is expected. Annotation ignored.' || - '%%' + '%checked[1]Checked (1, 2, 3)' || + '%checked[2]Checked (1)' || + '%checked[3]Checked (1)' || + '%checked[4]Checked (1, 2)%1, 2' || + '%checked[5]Checked ([1, 2)%[1, 2' || + '%checked[7]Checked (1000, 2000)%' + ); + ut.expect(l_actual).not_to_be_like('%test_case_args.checked[6]%'); + ut.expect(l_actual).to_be_like( + '%%Annotation "--%testcase" requires a JSON array or object, e.g. "--%testcase([1, 2])". Annotation ignored.' || + '%line 20%%' ); - ut.expect(l_actual).to_be_like('%test_case_args.checked[7]%'); - ut.expect(l_actual).not_to_be_like('%test_case_args.checked[_]%test_case_args.checked[_]%'); + ut.expect(l_actual).not_to_be_like('%invalid arguments%'); end; procedure testcase_json_arguments is @@ -2143,11 +2142,9 @@ create or replace package body test_suite_builder is ut3_develop.ut_annotation(14, 'test','Half of {a_amount} is {a_half}', 'checked'), ut3_develop.ut_annotation(15, 'testcase', '[2000, 1000]', 'checked'), ut3_develop.ut_annotation(16, 'testcase', '{"a_half": 5, "a_amount": 10}', 'checked'), - ut3_develop.ut_annotation(17, 'testcase', '[1, 2, 3]', 'checked'), - ut3_develop.ut_annotation(18, 'testcase', '{"a_x": 1}', 'checked'), - ut3_develop.ut_annotation(19, 'testcase', '{"a_amount": 1}', 'checked'), - ut3_develop.ut_annotation(20, 'testcase', '[1, 2', 'checked'), - ut3_develop.ut_annotation(21, 'testcase', chr(9) || '[6, 3]', 'checked') + ut3_develop.ut_annotation(17, 'testcase', '[8, 4, "extra"]', 'checked'), + ut3_develop.ut_annotation(18, 'testcase', '{"A_AMOUNT": 12, "A_Half": 6, "note": "x"}', 'checked'), + ut3_develop.ut_annotation(19, 'testcase', chr(9) || '[6, 3]', 'checked') ); --Act l_actual := invoke_builder_for_annotations(l_annotations, 'TEST_CASE_ARGS'); @@ -2158,41 +2155,9 @@ create or replace package body test_suite_builder is ut.expect(l_actual).to_be_like( '%checked[2]Half of 10 is 5%{"a_half": 5, "a_amount": 10}%' ); - ut.expect(l_actual).to_be_like( - '%' || - '%has invalid arguments: 3 value(s) given, but the procedure has 2 parameter(s). Annotation ignored.' || - '%has invalid arguments: the procedure has no parameter A_X. Annotation ignored.' || - '%has invalid arguments: no value for parameter(s) A_HALF. Annotation ignored.' || - '%has invalid arguments: it is not valid JSON. Annotation ignored.' || - '%%' - ); - ut.expect(l_actual).not_to_be_like('%test_case_args.checked[3]%'); - ut.expect(l_actual).to_be_like('%checked[7]Half of 6 is 3%'); - end; - - procedure testcase_overloads is - l_actual clob; - l_annotations ut3_develop.ut_annotations; - begin - --Arrange - l_annotations := ut3_develop.ut_annotations( - ut3_develop.ut_annotation(1, 'suite','Cool', null), - ut3_develop.ut_annotation(14, 'test','Overloaded', 'ovl'), - ut3_develop.ut_annotation(15, 'testcase', '[5]', 'ovl'), - ut3_develop.ut_annotation(16, 'testcase', '["x", 1]', 'ovl'), - ut3_develop.ut_annotation(17, 'testcase', '[1, 2, 3]', 'ovl'), - ut3_develop.ut_annotation(18, 'testcase', '[]', 'ovl') - ); - --Act - l_actual := invoke_builder_for_annotations(l_annotations, 'TEST_CASE_ARGS'); - --Assert - ut.expect(l_actual).to_be_like( - '%test_case_args.ovl[1]%test_case_args.ovl[2]%test_case_args.ovl[4]%' - ); - ut.expect(l_actual).to_be_like( - '%%has invalid arguments: 3 value(s) given, but the procedure has 1 parameter(s). Annotation ignored.%%' - ); - ut.expect(l_actual).not_to_be_like('%test_case_args.ovl[3]%'); + ut.expect(l_actual).to_be_like('%checked[3]Half of 8 is 4%'); + ut.expect(l_actual).to_be_like('%checked[4]Half of 12 is 6%'); + ut.expect(l_actual).to_be_like('%checked[5]Half of 6 is 3%'); end; end test_suite_builder; diff --git a/test/ut3_tester/core/test_suite_builder.pks b/test/ut3_tester/core/test_suite_builder.pks index dae8a7bcc..89f98ef34 100644 --- a/test/ut3_tester/core/test_suite_builder.pks +++ b/test/ut3_tester/core/test_suite_builder.pks @@ -201,20 +201,17 @@ create or replace package test_suite_builder is --%endcontext - --%context(test case argument checks) + --%context(test case arguments) --%beforeall(create_test_case_args_package) --%afterall(drop_test_case_args_package) - --%test(Gives a warning for each test case with invalid or no JSON arguments and skips it) - procedure testcase_invalid_arguments; + --%test(Creates a test for each test case, also an invalid one, and gives a warning for an empty annotation) + procedure testcase_every_case_is_a_test; - --%test(Checks JSON test case arguments and fills in the description) + --%test(Fills in the description, by position and by name, ignoring extra values and keys) procedure testcase_json_arguments; - --%test(Accepts arguments that fit one of the overloads, including an overload without parameters) - procedure testcase_overloads; - --%endcontext procedure create_test_case_args_package; diff --git a/test/ut3_tester/core/test_ut_utils.pkb b/test/ut3_tester/core/test_ut_utils.pkb index b74e07e84..0b1280251 100644 --- a/test/ut3_tester/core/test_ut_utils.pkb +++ b/test/ut3_tester/core/test_ut_utils.pkb @@ -385,10 +385,39 @@ end;'; begin ut.expect( ut3_develop.ut_utils.get_test_case_description( - 'Amount {1}, kind {a_kind}, unknown {3}', + '{1}: amount {1}, kind {a_kind}, also {A_Kind}', ut3_develop.ut_varchar2_list(null, 'A_KIND'), ut3_develop.ut_varchar2_list('100', q'['VIP']') ) - ).to_equal(q'[Amount 100, kind 'VIP', unknown {3}]'); + ).to_equal(q'[100: amount 100, kind 'VIP', also 'VIP']'); + end; + + procedure test_case_descr_unresolved is + begin + ut.expect( + ut3_develop.ut_utils.get_test_case_description( + 'Not existing {reference}', ut3_develop.ut_varchar2_list('a', 'b'), ut3_develop.ut_varchar2_list('4', '2') + ) + ).to_equal('Not existing {reference} (4, 2)'); + ut.expect( + ut3_develop.ut_utils.get_test_case_description( + 'Amount {1}, unknown {3}, none {0}', ut3_develop.ut_varchar2_list(null, null), ut3_develop.ut_varchar2_list('100', 'x') + ) + ).to_equal('Amount 100, unknown {3}, none {0} (100, x)'); + -- {} and { 1 } are no placeholders + ut.expect( + ut3_develop.ut_utils.get_test_case_description( + 'Set {} and { 1 }', ut3_develop.ut_varchar2_list(null), ut3_develop.ut_varchar2_list('7') + ) + ).to_equal('Set {} and { 1 } (7)'); + end; + + procedure test_case_descr_value_braces is + begin + ut.expect( + ut3_develop.ut_utils.get_test_case_description( + '{1} and {2}', ut3_develop.ut_varchar2_list(null, null), ut3_develop.ut_varchar2_list('{2}', 'b') + ) + ).to_equal('{2} and b'); end; procedure test_case_descr_shortens is diff --git a/test/ut3_tester/core/test_ut_utils.pks b/test/ut3_tester/core/test_ut_utils.pks index c9abe0f6a..de7860c0e 100644 --- a/test/ut3_tester/core/test_ut_utils.pks +++ b/test/ut3_tester/core/test_ut_utils.pks @@ -129,10 +129,16 @@ create or replace package test_ut_utils is --%test(Appends the arguments when the description has no placeholders) procedure test_case_descr_appends; - --%test(Replaces placeholders by position and by name) + --%test(Replaces placeholders by position and by name, not case-sensitive) procedure test_case_descr_placeholders; - --%test(Shortens values longer than 100 characters and appends the values when no appendix is given) + --%test(Appends the values when a placeholder refers to no value) + procedure test_case_descr_unresolved; + + --%test(Doesn't replace placeholders in values) + procedure test_case_descr_value_braces; + + --%test(Shortens values longer than 100 characters) procedure test_case_descr_shortens; --%test(Keeps a null description null) diff --git a/test/ut3_user/api/test_ut_test_cases.pkb b/test/ut3_user/api/test_ut_test_cases.pkb index 278d3b4c5..a00973dbb 100644 --- a/test/ut3_user/api/test_ut_test_cases.pkb +++ b/test/ut3_user/api/test_ut_test_cases.pkb @@ -49,9 +49,6 @@ end;~', '', a_name), '', a_body); procedure create_test_case_suites is pragma autonomous_transaction; - l_boolean_spec varchar2(4000); - l_boolean_body varchar2(4000); - l_wide_parameters varchar2(4000); begin execute immediate 'create or replace type test_case_pair force as object (amount number, half number)'; execute immediate 'create or replace type test_case_numbers force as table of number'; @@ -117,46 +114,6 @@ end;~'; ]'); end;~' ); - create_discount_suite( - 'tc_discount_cursor', - ' --%testcasesource(discount_cases)', - ' function discount_cases return sys_refcursor;', - q'~ - function discount_cases return sys_refcursor is - l_cursor sys_refcursor; - begin - open l_cursor for - select 500 as a_order_total, - 'REGULAR' as a_customer_type, - to_date('2026-03-15 14:30:00', 'yyyy-mm-dd hh24:mi:ss') as a_order_date, - to_timestamp('2026-03-01 00:00:00.000000', 'yyyy-mm-dd hh24:mi:ss.ff') as a_promo_start, - to_timestamp_tz('2026-03-31 23:59:59.999999 +02:00', 'yyyy-mm-dd hh24:mi:ss.ff tzh:tzm') as a_promo_end, - 0.05 as a_expected - from dual - union all - select 1000, 'REGULAR', - to_date('2026-04-01 09:00:00', 'yyyy-mm-dd hh24:mi:ss'), - to_timestamp('2026-03-01 00:00:00.000000', 'yyyy-mm-dd hh24:mi:ss.ff'), - to_timestamp_tz('2026-03-31 23:59:59.999999 +02:00', 'yyyy-mm-dd hh24:mi:ss.ff tzh:tzm'), - 0.1 - from dual - union all - select 50, 'VIP', - to_date('2026-03-20 10:00:00', 'yyyy-mm-dd hh24:mi:ss'), - to_timestamp('2026-03-01 00:00:00.000000', 'yyyy-mm-dd hh24:mi:ss.ff'), - to_timestamp_tz('2026-03-31 23:59:59.999999 -05:00', 'yyyy-mm-dd hh24:mi:ss.ff tzh:tzm'), - 0.25 - from dual - union all - select null, 'REGULAR', - to_date('2026-02-28 23:59:59', 'yyyy-mm-dd hh24:mi:ss'), - to_timestamp('2026-03-01 00:00:00.000000', 'yyyy-mm-dd hh24:mi:ss.ff'), - to_timestamp_tz('2026-03-31 23:59:59.999999 +02:00', 'yyyy-mm-dd hh24:mi:ss.ff tzh:tzm'), - 0 - from dual; - return l_cursor; - end;~' - ); execute immediate q'~create or replace package tc_inline as --%suite(Inline test cases) @@ -222,13 +179,38 @@ end;~'; --%testcase([1, 2]) procedure not_json(a_first number, a_second number); + --%test(Half of {a_amount} is {a_half}) + --%testcase([8, 4, "extra"]) + --%testcase({"a_amount": 6, "a_half": 3, "note": "six", "a_amount2": 1}) + procedure extras(a_amount number, a_half number); + + --%test(Duplicate {a_value}) + --%testcase([1]) + --%testcase([1]) + procedure duplicates(a_value number); + + --%test(Not existing {reference}) + --%testcase([4, 2]) + procedure unknown_placeholder(a_amount number, a_half number); + + --%test(Injection {1}) + --%testcase({"a_text": "'); delete from test_case_rows; --", "a_text'); delete from test_case_rows; --": 1}) + --%testcase(["x' || 'y"]) + --%testcase({"A_TEXT\"); delete from test_case_rows; --": 1, "a_text": "z"}) + procedure injection(a_text varchar2); + + --%test(Quoted parameter {1}) + --%testcase({"a'B": 1}) + --%testcase([1]) + procedure quoted_parameter("a'B" number); + --%test(More types) --%testcase([1.5, "n\u00e4", "P1DT2H", "P1Y2M", "0AFF", "long text"]) procedure more_types(a_double binary_double, a_national nvarchar2, a_ds interval day to second, a_ym interval year to month, a_raw raw, a_clob clob); --%test(No parameters) --%testcase([]) - --%testcase({}) + --%testcase([1]) procedure no_parameters; type t_record is record (a number); @@ -302,6 +284,27 @@ end;~'; begin ut3_develop.ut.expect(a_pair.amount).to_equal(1); end; + procedure extras(a_amount number, a_half number) is + begin + ut3_develop.ut.expect(a_amount / 2).to_equal(a_half); + end; + procedure duplicates(a_value number) is + begin + ut3_develop.ut.expect(a_value).to_equal(1); + end; + procedure unknown_placeholder(a_amount number, a_half number) is + begin + ut3_develop.ut.expect(a_amount / 2).to_equal(a_half); + end; + procedure injection(a_text varchar2) is + begin + ut3_develop.ut.expect(a_text).to_be_not_null(); + ut3_develop.ut.expect(a_text in ('''); delete from test_case_rows; --', 'x'' || ''y', 'z')).to_be_true(); + end; + procedure quoted_parameter("a'B" number) is + begin + ut3_develop.ut.expect("a'B").to_equal(1); + end; procedure more_types(a_double binary_double, a_national nvarchar2, a_ds interval day to second, a_ym interval year to month, a_raw raw, a_clob clob) is begin ut3_develop.ut.expect(a_double).to_equal(1.5d); @@ -446,6 +449,17 @@ end;~'; --%testcasesource(get_one) procedure overloaded(a_value number); procedure overloaded(a_value varchar2, a_other number); + + --%test(No parameters) + --%testcasesource(get_one) + procedure no_parameters; + + --%test(Shared source: amount {a_amount}) + --%testcasesource(tc_sources.get_cases) + procedure shared_source(a_amount number); + + --%test(Plain) + procedure plain; end;~'; execute immediate q'~create or replace package body tc_json_source as procedure fill_rows is @@ -624,317 +638,19 @@ end;~'; begin null; end; -end;~'; - - $if dbms_db_version.version >= 23 $then - l_boolean_spec := q'~ - --%test(Flag {a_flag} is {a_label}) - --%testcasesource(get_booleans) - procedure booleans(a_flag boolean, a_label varchar2); - function get_booleans return sys_refcursor;~'; - l_boolean_body := q'~ - procedure booleans(a_flag boolean, a_label varchar2) is - begin - ut3_develop.ut.expect(case when a_flag then 'yes' when not a_flag then 'no' else 'null' end).to_equal(a_label); - end; - function get_booleans return sys_refcursor is - l_cursor sys_refcursor; - begin - open l_cursor for - select true a_flag, 'yes' a_label from dual union all - select false, 'no' from dual union all - select cast(null as boolean), 'null' from dual; - return l_cursor; - end;~'; - $end - -- named arguments for 200 parameters are longer than the arguments of a test can be - for i in 1 .. 200 loop - l_wide_parameters := l_wide_parameters || case when i > 1 then ', ' end || 'c' || i || ' number'; - end loop; - execute immediate replace(q'~create or replace package tc_cursor_source as - --%suite(Cursor sources) - --%beforeall(fill_rows) - - c_limit constant number := 100; - procedure fill_rows; - procedure delete_rows; - - --%test(Cursor case {label} with limit {a_limit}) - --%testcasesource(get_by_name) - procedure by_name(a_day date, a_limit number, a_pair test_case_pair); - function get_by_name return sys_refcursor; - - --%test(Position: half of {1} is {2}) - --%testcasesource(get_by_position) - procedure by_position(a_amount number, a_half number); - function get_by_position return sys_refcursor; - - --%test(Snapshot: half of {a_amount} is {a_half}) - --%testcasesource(get_rows) - --%beforetest(delete_rows) - procedure snapshot(a_amount number, a_half number); - function get_rows return sys_refcursor; - - --%test(No rows) - --%testcasesource(get_no_rows) - procedure no_rows(a_value number); - function get_no_rows return sys_refcursor; - - --%test(Unsupported column) - --%testcasesource(get_xml) - procedure unsupported_column(a_xml clob); - function get_xml return sys_refcursor; - - --%test(Column that doesn't fit) - --%testcasesource(get_wrong_column) - procedure column_doesnt_fit(a_pair test_case_pair); - function get_wrong_column return sys_refcursor; - - --%test(Many rows) - --%testcasesource(get_many) - procedure many_rows(a_value number); - function get_many return sys_refcursor; - - --%test(Cursor types) - --%testcasesource(get_types) - procedure types( - a_char char, a_nchar nchar, a_nvarchar nvarchar2, a_float binary_float, a_double binary_double, - a_ltz timestamp with local time zone, a_ds interval day to second, a_ym interval year to month, - a_clob clob, a_nclob nclob, a_blob blob, a_raw raw, a_numbers test_case_numbers - ); - function get_types return sys_refcursor; - - --%test(Too many columns) - --%testcasesource(get_wide) - procedure too_many_columns(); - function get_wide return sys_refcursor; - - --%test(Position count) - --%testcasesource(get_three) - procedure position_count(a_amount number, a_half number); - function get_three return sys_refcursor; - - --%test(Misspelled column) - --%testcasesource(get_misspelled) - procedure misspelled_column(a_amount number, a_half number := 0); - function get_misspelled return sys_refcursor; - - --%test(Missing column) - --%testcasesource(get_amount) - procedure missing_column(a_amount number, a_half number); - function get_amount return sys_refcursor; - - --%test(Duplicate column) - --%testcasesource(get_duplicate) - procedure duplicate_column(a_amount number); - function get_duplicate return sys_refcursor; - - --%test(Lower case {a_amount}) - --%testcasesource(get_lower_case) - procedure lower_case_column(a_amount number, a_half number := 2); - function get_lower_case return sys_refcursor; - - --%test(Overloaded) - --%testcasesource(get_amount) - procedure overloaded(a_amount number); - procedure overloaded(a_amount varchar2, a_other number); -~' || l_boolean_spec || q'~ -end;~', '', l_wide_parameters); - execute immediate replace(q'~create or replace package body tc_cursor_source as - procedure fill_rows is - begin - insert into test_case_rows values (10, 5); - insert into test_case_rows values (3, 2); - insert into test_case_rows values (4, 2); - end; - procedure delete_rows is - begin - delete from test_case_rows; - end; - procedure by_name(a_day date, a_limit number, a_pair test_case_pair) is - begin - ut3_develop.ut.expect(a_day).to_be_between(trunc(sysdate), trunc(sysdate) + 1); - ut3_develop.ut.expect(a_limit).to_be_greater_or_equal(c_limit); - ut3_develop.ut.expect(a_pair.amount / 2).to_equal(a_pair.half); - end; - function get_by_name return sys_refcursor is - l_cursor sys_refcursor; - begin - open l_cursor for - select 'today' label, trunc(sysdate) a_day, c_limit a_limit, test_case_pair(8, 4) a_pair from dual - union all - select 'tomorrow', trunc(sysdate) + 1, c_limit * 2, test_case_pair(6, 3) from dual - order by 1; - return l_cursor; - end; - procedure by_position(a_amount number, a_half number) is - begin - ut3_develop.ut.expect(a_amount / 2).to_equal(a_half); - end; - function get_by_position return sys_refcursor is - l_cursor sys_refcursor; - begin - open l_cursor for select 4 x, 2 y from dual union all select 10, 5 from dual; - return l_cursor; - end; - procedure snapshot(a_amount number, a_half number) is - begin - ut3_develop.ut.expect(a_amount).to_be_not_null(); - ut3_develop.ut.expect(a_half).to_be_not_null(); - end; - function get_rows return sys_refcursor is - l_cursor sys_refcursor; - begin - open l_cursor for select a_amount, a_half from test_case_rows order by a_amount; - return l_cursor; - end; - procedure no_rows(a_value number) is - begin - null; - end; - function get_no_rows return sys_refcursor is - l_cursor sys_refcursor; - begin - open l_cursor for select 1 a_value from dual where 1 = 0; - return l_cursor; - end; - procedure unsupported_column(a_xml clob) is - begin - null; - end; - function get_xml return sys_refcursor is - l_cursor sys_refcursor; - begin - open l_cursor for select xmltype('') a_xml from dual; - return l_cursor; - end; - procedure column_doesnt_fit(a_pair test_case_pair) is - begin - null; - end; - function get_wrong_column return sys_refcursor is - l_cursor sys_refcursor; - begin - open l_cursor for select 1 a_pair from dual; - return l_cursor; - end; - procedure many_rows(a_value number) is - begin - ut3_develop.ut.expect(a_value).to_be_between(1, 300); - end; - function get_many return sys_refcursor is - l_cursor sys_refcursor; - begin - open l_cursor for select level a_value from dual connect by level <= 300; - return l_cursor; - end; - procedure types( - a_char char, a_nchar nchar, a_nvarchar nvarchar2, a_float binary_float, a_double binary_double, - a_ltz timestamp with local time zone, a_ds interval day to second, a_ym interval year to month, - a_clob clob, a_nclob nclob, a_blob blob, a_raw raw, a_numbers test_case_numbers - ) is - begin - ut3_develop.ut.expect(a_char).to_equal('a '); - ut3_develop.ut.expect(a_nchar = n'b ').to_be_true(); - ut3_develop.ut.expect(a_nvarchar = n'c').to_be_true(); - ut3_develop.ut.expect(a_float = 1.5f).to_be_true(); - ut3_develop.ut.expect(a_double = 2.5d).to_be_true(); - ut3_develop.ut.expect(cast(a_ltz as timestamp)).to_equal(timestamp '2026-03-31 12:00:00'); - ut3_develop.ut.expect(a_ds).to_equal(interval '1 02:00:00' day to second); - ut3_develop.ut.expect(a_ym).to_equal(interval '1-2' year to month); - ut3_develop.ut.expect(a_clob).to_equal(to_clob('long')); - ut3_develop.ut.expect(to_clob(a_nclob)).to_equal(to_clob('nlong')); - ut3_develop.ut.expect(a_blob).to_equal(to_blob(hextoraw('0AFF'))); - ut3_develop.ut.expect(rawtohex(a_raw)).to_equal('0BEE'); - ut3_develop.ut.expect(a_numbers.count).to_equal(2); - end; - function get_types return sys_refcursor is - l_cursor sys_refcursor; - begin - open l_cursor for - select cast('a' as char(3)) a_char, cast(n'b' as nchar(2)) a_nchar, cast(n'c' as nvarchar2(10)) a_nvarchar, - cast(1.5 as binary_float) a_float, cast(2.5 as binary_double) a_double, - cast(timestamp '2026-03-31 12:00:00' as timestamp with local time zone) a_ltz, - interval '1 02:00:00' day to second a_ds, interval '1-2' year to month a_ym, - to_clob('long') a_clob, to_nclob('nlong') a_nclob, to_blob(hextoraw('0AFF')) a_blob, hextoraw('0BEE') a_raw, - test_case_numbers(1, 2) a_numbers - from dual; - return l_cursor; - end; - procedure too_many_columns() is - begin - null; - end; - function get_wide return sys_refcursor is - l_cursor sys_refcursor; - l_select varchar2(32767); - begin - for i in 1 .. 200 loop - l_select := l_select || case when i > 1 then ', ' end || i || ' c' || i; - end loop; - open l_cursor for 'select ' || l_select || ' from dual'; - return l_cursor; - end; - procedure position_count(a_amount number, a_half number) is - begin - null; - end; - function get_three return sys_refcursor is - l_cursor sys_refcursor; - begin - open l_cursor for select 4 x, 2 y, 0 z from dual; - return l_cursor; - end; - procedure misspelled_column(a_amount number, a_half number := 0) is - begin - null; - end; - function get_misspelled return sys_refcursor is - l_cursor sys_refcursor; - begin - open l_cursor for select 4 a_amount, 2 a_halv from dual; - return l_cursor; - end; - procedure missing_column(a_amount number, a_half number) is - begin - null; - end; - function get_amount return sys_refcursor is - l_cursor sys_refcursor; - begin - open l_cursor for select 4 a_amount from dual; - return l_cursor; - end; - procedure duplicate_column(a_amount number) is + procedure no_parameters is begin null; end; - function get_duplicate return sys_refcursor is - l_cursor sys_refcursor; + procedure shared_source(a_amount number) is begin - open l_cursor for select 4 a_amount, 5 "a_amount" from dual; - return l_cursor; + ut3_develop.ut.expect(a_amount).to_be_between(4, 10); end; - procedure lower_case_column(a_amount number, a_half number := 2) is - begin - ut3_develop.ut.expect(a_amount / 2).to_equal(a_half); - end; - function get_lower_case return sys_refcursor is - l_cursor sys_refcursor; - begin - open l_cursor for select 4 "a_amount" from dual; - return l_cursor; - end; - procedure overloaded(a_amount number) is - begin - null; - end; - procedure overloaded(a_amount varchar2, a_other number) is + procedure plain is begin null; end; -~' || l_boolean_body || q'~ -end;~', '', l_wide_parameters); +end;~'; execute immediate q'~create or replace package tc_times as --%suite(Dates and times) @@ -944,11 +660,6 @@ end;~', '', l_wide_parameters); --%testcase({"a_date": "2026-03-31T12:00:00 -05:00", "a_ts": "2026-03-31T12:00:00.123456", "a_tz": "2026-03-31T12:00:00", "a_ltz": "2026-03-31T12:00:00Z"}) procedure json_strings(a_date date, a_ts timestamp, a_tz timestamp with time zone, a_ltz timestamp with local time zone); - --%test(Cursor) - --%testcasesource(get_times) - procedure cursor_values(a_date date, a_ts timestamp, a_tz timestamp with time zone, a_ltz timestamp with local time zone); - function get_times return sys_refcursor; - --%test(Date only {1}) --%testcase(["2026-03-15", "2026-03-15"]) procedure date_only(a_date date, a_ts timestamp); @@ -975,21 +686,6 @@ end;~'; begin check_values(a_date, a_ts, a_tz, a_ltz); end; - procedure cursor_values(a_date date, a_ts timestamp, a_tz timestamp with time zone, a_ltz timestamp with local time zone) is - begin - check_values(a_date, a_ts, a_tz, a_ltz); - end; - function get_times return sys_refcursor is - l_cursor sys_refcursor; - begin - open l_cursor for - select to_timestamp_tz('2026-03-31 12:00:00 -05:00', 'yyyy-mm-dd hh24:mi:ss tzh:tzm') a_date, - to_timestamp('2026-03-31 12:00:00.123456', 'yyyy-mm-dd hh24:mi:ss.ff6') a_ts, - cast(timestamp '2026-03-31 12:00:00' as timestamp with time zone) a_tz, - to_timestamp_tz('2026-03-31 12:00:00 +00:00', 'yyyy-mm-dd hh24:mi:ss tzh:tzm') a_ltz - from dual; - return l_cursor; - end; procedure date_only(a_date date, a_ts timestamp) is begin ut3_develop.ut.expect(to_char(a_date, 'yyyy-mm-dd hh24:mi:ss')).to_equal('2026-03-15 00:00:00'); @@ -1009,8 +705,7 @@ end;~'; select object_name, object_type from user_objects where object_name in ( - 'TC_DISCOUNT_PLSQL', 'TC_DISCOUNT_JSON', 'TC_DISCOUNT_SOURCE', 'TC_DISCOUNT_CURSOR', - 'TC_INLINE', 'TC_SOURCES', 'TC_JSON_SOURCE', 'TC_CURSOR_SOURCE', 'TC_TIMES', 'GET_DISCOUNT' + 'TC_DISCOUNT_JSON', 'TC_DISCOUNT_SOURCE', 'TC_INLINE', 'TC_SOURCES', 'TC_JSON_SOURCE', 'TC_TIMES', 'GET_DISCOUNT' ) and object_type in ('PACKAGE', 'FUNCTION') ) loop @@ -1051,6 +746,13 @@ end;~'; return ut3_tester_helper.main_helper.table_to_clob(l_results); end; + function run_report(a_paths ut3_develop.ut_varchar2_list) return clob is + l_results ut3_develop.ut_varchar2_list; + begin + select * bulk collect into l_results from table(ut3_develop.ut.run(a_paths)); + return ut3_tester_helper.main_helper.table_to_clob(l_results); + end; + -- the lines of the report that start with a_prefix, without execution times function report_lines(a_path varchar2, a_prefix varchar2) return varchar2 is l_results ut3_develop.ut_varchar2_list; @@ -1078,12 +780,6 @@ end;~'; ut.expect(run_report('tc_discount_source')).to_be_like('%4 tests, 0 failed, 0 errored, 0 disabled, 0 warning(s)%'); end; - procedure discount_cursor_source is - begin - ut.expect(report_lines('tc_discount_cursor', 'Discount for')).to_equal(c_discount_cases); - ut.expect(run_report('tc_discount_cursor')).to_be_like('%4 tests, 0 failed, 0 errored, 0 disabled, 0 warning(s)%'); - end; - procedure discount_independent_of_nls is l_lines varchar2(32767); begin @@ -1091,7 +787,7 @@ end;~'; for r in ( select column_value suite from table(ut3_develop.ut_varchar2_list( - 'tc_discount_json', 'tc_discount_source', 'tc_discount_cursor' + 'tc_discount_json', 'tc_discount_source' )) ) loop l_lines := report_lines(r.suite, 'Discount for'); @@ -1208,8 +904,9 @@ end;~'; procedure testcase_not_json is begin ut.expect(run_report('tc_inline.not_json')).to_be_like( - '%Not JSON (1, 2) [%Annotation "--%testcase" has invalid arguments: a JSON array or object is expected. Annotation ignored.%' || - '1 tests, 0 failed, 0 errored, 0 disabled, 1 warning(s)%' + '%Not JSON (1, 2) [%Not JSON (1, 2) [%' || + 'not_json[1]%Invalid JSON test case: a JSON array or object is expected.%' || + '2 tests, 0 failed, 1 errored, 0 disabled, 0 warning(s)%' ); end; @@ -1221,6 +918,36 @@ end;~'; ); end; + procedure testcase_extra_values is + begin + ut.expect(report_lines('tc_inline.extras', 'Half of')).to_equal( + 'Half of 8 is 4' || chr(10) || + 'Half of 6 is 3' + ); + ut.expect(run_report('tc_inline.extras')).to_be_like('%2 tests, 0 failed, 0 errored, 0 disabled, 0 warning(s)%'); + end; + + procedure testcase_duplicates is + begin + ut.expect(run_report('tc_inline.duplicates')).to_be_like('%Duplicate 1 [%Duplicate 1 [%2 tests, 0 failed, 0 errored%'); + end; + + procedure testcase_unknown_placeholder is + begin + ut.expect(report_lines('tc_inline.unknown_placeholder', 'Not existing')).to_equal('Not existing {reference} (4, 2)'); + end; + + procedure testcase_injection is + l_count integer; + begin + -- the table is created by the beforeall, so it is accessed with dynamic SQL + execute immediate 'insert into test_case_rows values (1, 1)'; + ut.expect(run_report('tc_inline.injection')).to_be_like('%3 tests, 0 failed, 0 errored%'); + ut.expect(run_report('tc_inline.quoted_parameter')).to_be_like('%2 tests, 0 failed, 0 errored%'); + execute immediate 'select count(*) from test_case_rows' into l_count; + ut.expect(l_count).to_equal(1); + end; + procedure source_json_after_beforeall is begin ut.expect(run_report('tc_json_source.from_table')).to_be_like( @@ -1260,8 +987,8 @@ end;~'; '%The --%testcasesource function failed.%ORA-40587%1 tests, 0 failed, 1 errored%' ); ut.expect(run_report('tc_json_source.scalar_element')).to_be_like( - '%The --%testcasesource function get_scalar returned element 2, which is neither a JSON array nor a JSON object.%' || - '1 tests, 0 failed, 1 errored%' + '%Scalar element (1) [%Scalar element (2) [%' || + 'scalar_element[2]%Invalid JSON test case: a JSON array or object is expected.%2 tests, 0 failed, 1 errored%' ); ut.expect(run_report('tc_json_source.invalid_json')).to_be_like( '%The --%testcasesource function failed.%ORA-40441%1 tests, 0 failed, 1 errored%' @@ -1271,10 +998,10 @@ end;~'; procedure source_function_errors is begin ut.expect(run_report('tc_json_source.wrong_return_type')).to_be_like( - '%The --%testcasesource function get_number must return json_array_t or sys_refcursor, not NUMBER.%1 tests, 0 failed, 1 errored%' + '%The --%testcasesource function get_number must return json_array_t, not NUMBER.%1 tests, 0 failed, 1 errored%' ); ut.expect(run_report('tc_json_source.json_as_text')).to_be_like( - '%The --%testcasesource function get_clob must return json_array_t or sys_refcursor, not CLOB.%1 tests, 0 failed, 1 errored%' + '%The --%testcasesource function get_clob must return json_array_t, not CLOB.%1 tests, 0 failed, 1 errored%' ); ut.expect(run_report('tc_json_source.missing_function')).to_be_like( '%The --%testcasesource function get_nothing doesn''t exist or can''t be called without arguments.%1 tests, 0 failed, 1 errored%' @@ -1296,7 +1023,10 @@ end;~'; procedure testcase_without_parameters is begin - ut.expect(run_report('tc_inline.no_parameters')).to_be_like('%2 tests, 0 failed, 0 errored%'); + ut.expect(run_report('tc_inline.no_parameters')).to_be_like( + '%no_parameters[1]%Invalid JSON test case: the procedure NO_PARAMETERS has no parameters, so it can''t be run with test cases.%' || + 'no_parameters[2]%Invalid JSON test case: the procedure NO_PARAMETERS has no parameters%2 tests, 0 failed, 2 errored%' + ); end; procedure testcase_json_record_parameter is @@ -1326,145 +1056,77 @@ end;~'; ); end; - procedure source_cursor_types is - begin - ut.expect(run_report('tc_cursor_source.types')).to_be_like( - '%Cursor types (a , b , c, 1.5, 2.5, %, long, nlong, , 0BEE, <%TEST_CASE_NUMBERS>) [%1 tests, 0 failed, 0 errored%' - ); - end; - - procedure source_cursor_too_many_columns is - begin - ut.expect(run_report('tc_cursor_source.too_many_columns')).to_be_like( - '%The --%testcasesource function get_wide returned more columns than can be passed to the test procedure.%1 tests, 0 failed, 1 errored%' - ); - end; - - procedure source_cursor_position_count is - begin - ut.expect(run_report('tc_cursor_source.position_count')).to_be_like( - '%The --%testcasesource function get_three returned 3 column(s) and none is named like a parameter, but the test procedure has 2 parameter(s);%1 tests, 0 failed, 1 errored%' - ); - end; - - procedure source_cursor_misspelled_column is - begin - ut.expect(run_report('tc_cursor_source.misspelled_column')).to_be_like( - '%The --%testcasesource function get_misspelled returned column A_HALV, which is no parameter of the test procedure and isn''t used in the description.%1 tests, 0 failed, 1 errored%' - ); - end; - - procedure source_cursor_missing_column is - begin - ut.expect(run_report('tc_cursor_source.missing_column')).to_be_like( - '%The --%testcasesource function get_amount returned no column for parameter A_HALF, which has no default value.%1 tests, 0 failed, 1 errored%' - ); - end; - - procedure source_cursor_duplicate_column is - begin - ut.expect(run_report('tc_cursor_source.duplicate_column')).to_be_like( - '%The --%testcasesource function get_duplicate returned columns A_AMOUNT and a_amount for the same parameter A_AMOUNT.%1 tests, 0 failed, 1 errored%' - ); - end; - - procedure source_cursor_lower_case_column is - begin - ut.expect(run_report('tc_cursor_source.lower_case_column')).to_be_like('%Lower case 4 [%1 tests, 0 failed, 0 errored%'); - end; - - procedure source_cursor_overloaded is - begin - ut.expect(run_report('tc_cursor_source.overloaded')).to_be_like( - '%The --%testcasesource function get_amount can''t be used with the overloaded procedure OVERLOADED.%1 tests, 0 failed, 1 errored%' - ); - end; - procedure source_json_values_dont_fit is begin ut.expect(run_report('tc_json_source.mismatching')).to_be_like( '%mismatching[2]%ORA-01722%' || - 'mismatching[3]%Invalid JSON test case: 4 value(s) given, but the procedure has 2 parameter(s).%' || - 'mismatching[4]%Invalid JSON test case: the procedure has no parameter a_x.%' || + 'mismatching[4]%Invalid JSON test case: no value for parameter A_NUMBER, which has no default value.%' || 'mismatching[5]%Invalid JSON test case: parameter A_NUMBER is given twice.%' || 'mismatching[6]%' || 'mismatching[7]%Invalid JSON test case: no value for parameter A_NUMBER, which has no default value.%' || - '7 tests, 0 failed, 6 errored%' + '7 tests, 0 failed, 5 errored%' ); end; - procedure source_json_long_values is - begin - ut.expect(run_report('tc_json_source.long_values')).to_be_like('%1 tests, 0 failed, 0 errored%'); - end; - - procedure source_no_description is + procedure source_without_parameters is begin - ut.expect(run_report('tc_json_source.no_description')).to_be_like('%no_description[1] [%1 tests, 0 failed, 0 errored%'); - end; - - procedure source_cursor_by_name is - begin - ut.expect(report_lines('tc_cursor_source.by_name', 'Cursor case')).to_equal( - 'Cursor case today with limit 100' || chr(10) || - 'Cursor case tomorrow with limit 200' + ut.expect(run_report('tc_json_source.no_parameters')).to_be_like( + '%no_parameters[1]%Invalid JSON test case: the procedure NO_PARAMETERS has no parameters, so it can''t be run with test cases.%' || + '1 tests, 0 failed, 1 errored%' ); - ut.expect(run_report('tc_cursor_source.by_name')).to_be_like('%2 tests, 0 failed, 0 errored%'); end; - procedure source_cursor_by_position is + procedure source_shared is begin - ut.expect(run_report('tc_cursor_source.by_position')).to_be_like( - '%Position: half of 4 is 2 [%Position: half of 10 is 5 [%2 tests, 0 failed, 0 errored%' + ut.expect(run_report('tc_json_source.shared_source')).to_be_like( + '%Shared source: amount 4 [%Shared source: amount 10 [%2 tests, 0 failed, 0 errored%' ); end; - procedure source_cursor_snapshot is + procedure source_single_case_by_path is begin - ut.expect(run_report('tc_cursor_source.snapshot')).to_be_like('%3 tests, 0 failed, 0 errored%'); - end; - - procedure source_cursor_no_rows is - begin - ut.expect(run_report('tc_cursor_source.no_rows')).to_be_like( - '%The --%testcasesource function returned no test cases.%0 tests, 0 failed, 0 errored, 0 disabled, 1 warning(s)%' + ut.expect(run_report('tc_json_source.from_table[2]')).to_be_like( + '%Half of 4 from table is 2 [%1 tests, 0 failed, 0 errored, 0 disabled, 0 warning(s)%' ); - end; - - procedure source_cursor_unsupported_column is - begin - ut.expect(run_report('tc_cursor_source.unsupported_column')).to_be_like( - '%The --%testcasesource function get_xml returned column A_XML, which has a data type that can''t be passed to the test: XMLTYPE.%' || - '1 tests, 0 failed, 1 errored%' + ut.expect(run_report(':tc_json_source.from_table[3]')).to_be_like('%Half of 10 from table is 5 [%1 tests, 0 failed, 0 errored%'); + ut.expect( + run_report(ut3_develop.ut_varchar2_list('tc_json_source.from_table[1]', 'tc_json_source.from_table[3]')) + ).to_be_like('%Half of 3 from table is 2 [%Half of 10 from table is 5 [%2 tests, 1 failed, 0 errored%'); + ut.expect( + run_report(ut3_develop.ut_varchar2_list('tc_json_source.from_table[1]', 'tc_json_source.from_table')) + ).to_be_like('%3 tests, 1 failed, 0 errored%'); + ut.expect( + run_report(ut3_develop.ut_varchar2_list('tc_json_source.from_table[1]', 'tc_json_source')) + ).to_be_like('%Half of 3 from table is 2 [%Half of 4 from table is 2 [%Half of 10 from table is 5 [%'); + end; + + procedure source_case_number_too_high is + begin + ut.expect(run_report('tc_json_source.from_table[9]')).to_be_like( + '%Test case 9 doesn''t exist, the --%testcasesource function returned 3 test case(s).%0 tests, 0 failed, 0 errored, 0 disabled, 1 warning(s)%' ); end; - procedure source_cursor_column_doesnt_fit is + procedure source_case_number_on_plain_test is + l_results ut3_develop.ut_varchar2_list; begin - ut.expect(run_report('tc_cursor_source.column_doesnt_fit')).to_be_like( - '%The --%testcasesource function get_wrong_column returned column A_PAIR of type NUMBER, which can''t be passed to parameter A_PAIR of type %.TEST_CASE_PAIR.%1 tests, 0 failed, 1 errored%' - ); + select * bulk collect into l_results from table(ut3_develop.ut.run('tc_json_source.plain[1]')); end; - procedure source_cursor_many_rows is + procedure source_json_long_values is begin - ut.expect(run_report('tc_cursor_source.many_rows')).to_be_like('%300 tests, 0 failed, 0 errored%'); + ut.expect(run_report('tc_json_source.long_values')).to_be_like('%1 tests, 0 failed, 0 errored%'); end; - $if dbms_db_version.version >= 23 $then - procedure source_cursor_booleans is + procedure source_no_description is begin - ut.expect(run_report('tc_cursor_source.booleans')).to_be_like( - '%Flag true is yes [%Flag false is no [%Flag null is null [%3 tests, 0 failed, 0 errored%' - ); + ut.expect(run_report('tc_json_source.no_description')).to_be_like('%no_description[1] [%1 tests, 0 failed, 0 errored%'); end; - $end - procedure times_json_and_cursor_alike is + procedure times_json is begin set_other_session(); - ut.expect(run_report('tc_times.json_strings'), 'JSON').to_be_like('%2 tests, 0 failed, 0 errored%'); - ut.expect(run_report('tc_times.cursor_values'), 'cursor').to_be_like('%1 tests, 0 failed, 0 errored%'); + ut.expect(run_report('tc_times.json_strings')).to_be_like('%2 tests, 0 failed, 0 errored%'); restore_session(); exception when others then diff --git a/test/ut3_user/api/test_ut_test_cases.pks b/test/ut3_user/api/test_ut_test_cases.pks index 12716ffda..7af02dea8 100644 --- a/test/ut3_user/api/test_ut_test_cases.pks +++ b/test/ut3_user/api/test_ut_test_cases.pks @@ -16,9 +16,6 @@ create or replace package test_ut_test_cases is --%test(Runs test cases returned as json_array_t) procedure discount_json_source; - --%test(Runs test cases returned as cursor) - procedure discount_cursor_source; - --%test(Gives the same results when NLS settings and session time zone differ) procedure discount_independent_of_nls; @@ -63,16 +60,28 @@ create or replace package test_ut_test_cases is --%test(Reports JSON test cases of overloaded procedures as errored) procedure testcase_json_overloaded; - --%test(Skips a test case that is no JSON array or object with a warning) + --%test(Reports a test case that is no JSON array or object as errored) procedure testcase_not_json; + --%test(Ignores values and keys beyond the parameters) + procedure testcase_extra_values; + + --%test(Runs identical test cases each) + procedure testcase_duplicates; + + --%test(Appends the values when a placeholder refers to no value) + procedure testcase_unknown_placeholder; + + --%test(Passes keys and values with quotes and SQL as data, never as code) + procedure testcase_injection; + --%test(Reports test cases whose arguments don't fit the parameters as errored and runs the others) procedure testcase_arguments_dont_fit; --%test(Converts JSON values to BINARY_DOUBLE, NVARCHAR2, intervals, RAW and CLOB) procedure testcase_json_more_types; - --%test(Runs empty JSON arrays and objects for procedures without parameters) + --%test(Reports test cases of a procedure without parameters as errored) procedure testcase_without_parameters; --%test(Reports a JSON test case for a PL/SQL record parameter as errored, naming the type) @@ -97,10 +106,10 @@ create or replace package test_ut_test_cases is --%test(Gives a warning for an empty array, null and json_arrayagg over no rows with nvl) procedure source_json_no_test_cases; - --%test(Reports the test as errored when the function doesn't return a JSON array of arrays and objects) + --%test(Reports the test as errored when the function doesn't return a JSON array, and an element that is no array or object as errored test case) procedure source_json_invalid_result; - --%test(Reports the test as errored when the function doesn't exist, fails or returns another type than json_array_t or sys_refcursor) + --%test(Reports the test as errored when the function doesn't exist, fails or returns another type than json_array_t) procedure source_function_errors; --%test(Doesn't call the function of a disabled test) @@ -118,66 +127,28 @@ create or replace package test_ut_test_cases is --%test(Reports JSON test cases of an overloaded procedure as errored) procedure source_json_overloaded; - --%endcontext - - --%context(--%testcasesource returning a cursor) - - --%test(Passes columns by name, with sysdate, constants and object types, and uses other columns in the description) - procedure source_cursor_by_name; - - --%test(Passes columns by position when no column is named like a parameter) - procedure source_cursor_by_position; - - --%test(Passes the rows fetched before the first test case even when they are deleted) - procedure source_cursor_snapshot; - - --%test(Gives a warning when the cursor returns no rows) - procedure source_cursor_no_rows; - - --%test(Reports the test as errored when a column has a type that can't be passed) - procedure source_cursor_unsupported_column; - - --%test(Reports the test as errored when a column doesn't fit its parameter) - procedure source_cursor_column_doesnt_fit; - - --%test(Runs many test cases) - procedure source_cursor_many_rows; - - --%test(Passes columns of all supported types and shows them in the description) - procedure source_cursor_types; - - --%test(Reports the test as errored when the cursor has more columns than can be passed) - procedure source_cursor_too_many_columns; - - --%test(Reports the test as errored when no column is named like a parameter and the number of columns doesn't match) - procedure source_cursor_position_count; - - --%test(Reports the test as errored when a column is no parameter and isn't used in the description) - procedure source_cursor_misspelled_column; - - --%test(Reports the test as errored when a parameter without default has no column) - procedure source_cursor_missing_column; + --%test(Reports test cases of a procedure without parameters as errored) + procedure source_without_parameters; - --%test(Reports the test as errored when two columns are named like the same parameter) - procedure source_cursor_duplicate_column; + --%test(Uses one source for tests with different parameters) + procedure source_shared; - --%test(Matches column names to parameters not case-sensitive and uses defaults of parameters without column) - procedure source_cursor_lower_case_column; + --%test(Runs single test cases given by path, and all when the test is also given as a whole) + procedure source_single_case_by_path; - --%test(Reports the test as errored when the test procedure is overloaded) - procedure source_cursor_overloaded; + --%test(Gives a warning for a test case number beyond the test cases the function returned) + procedure source_case_number_too_high; - $if dbms_db_version.version >= 23 $then - --%test(Passes BOOLEAN columns) - procedure source_cursor_booleans; - $end + --%test(Raises an error for a test case number of a test without test cases) + --%throws(ut3_develop.ut_utils.gc_suite_package_not_found) + procedure source_case_number_on_plain_test; --%endcontext --%context(dates and times) - --%test(Converts date and time strings of JSON like the values of a cursor) - procedure times_json_and_cursor_alike; + --%test(Converts date and time strings independent of NLS settings and session time zone) + procedure times_json; --%test(Converts dates without time) procedure times_date_only; From aa2fd019e125493bf759a6d138f60e874fe3c9cc Mon Sep 17 00:00:00 2001 From: Jakob Drees <32562853+WayneNani@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:47:28 +0100 Subject: [PATCH 3/3] Test get_suites_info and is_test with test cases, document deterministic sources Co-Authored-By: Claude Opus 5.5 --- docs/userguide/annotations.md | 7 ++++++ test/ut3_user/api/test_ut_test_cases.pkb | 29 ++++++++++++++++++++++++ test/ut3_user/api/test_ut_test_cases.pks | 10 ++++++++ 3 files changed, 46 insertions(+) diff --git a/docs/userguide/annotations.md b/docs/userguide/annotations.md index e2b97cfb8..18401381f 100644 --- a/docs/userguide/annotations.md +++ b/docs/userguide/annotations.md @@ -539,6 +539,13 @@ It gives the same test cases and descriptions as the `--%testcase` example above A number beyond the test cases the function returns gives a warning. When the test is also selected as a whole (e.g. by its package), all its test cases run. +!!! note "Deterministic test cases" + A function that uses `sysdate`, `systimestamp`, sequences or data from tables isn't deterministic: it can return other test cases in each run. + Such tests aren't repeatable: a test can fail in one run and pass in the next, and the same number (e.g. `[2]`) can select another test case. + Make such tests pass in every run: derive the expected values from the same inputs (e.g. both from `sysdate`), + and read test data that `--%beforeall` creates rather than data that changes between runs. + The function should also have no side effects, as it is called in each run: don't change data in it, use `--%beforeall` for that. + #### JSON values JSON values of `--%testcase` and `--%testcasesource` are converted to the data type of the parameter they are passed to: diff --git a/test/ut3_user/api/test_ut_test_cases.pkb b/test/ut3_user/api/test_ut_test_cases.pkb index a00973dbb..c2d4110bf 100644 --- a/test/ut3_user/api/test_ut_test_cases.pkb +++ b/test/ut3_user/api/test_ut_test_cases.pkb @@ -1123,6 +1123,35 @@ end;~'; ut.expect(run_report('tc_json_source.no_description')).to_be_like('%no_description[1] [%1 tests, 0 failed, 0 errored%'); end; + procedure runner_get_suites_info is + l_expected sys_refcursor; + l_actual sys_refcursor; + begin + open l_expected for + select 'HALF[1]' item_name, 'Half of 2000 is 1000' item_description, 'UT_TEST' item_type, 'tc_inline.half[1]' path from dual union all + select 'HALF[2]', 'Half of 10 is 5', 'UT_TEST', 'tc_inline.half[2]' from dual union all + select 'HALF[3]', 'Half of 3 is 2', 'UT_TEST', 'tc_inline.half[3]' from dual union all + select 'HALF[4]', 'Half of 8 is 4', 'UT_TEST', 'tc_inline.half[4]' from dual union all + select 'HALF[5]', 'Half of 1 is 1', 'UT_TEST', 'tc_inline.half[5]' from dual union all + select 'FROM_TABLE', 'Half of {a_amount} from table is {a_half}', 'UT_TEST', 'tc_json_source.from_table' from dual; + open l_actual for + select item_name, item_description, item_type, path + from table(ut3_develop.ut_runner.get_suites_info('UT3_USER', 'TC_INLINE')) + where item_name like 'HALF%' + union all + select item_name, item_description, item_type, path + from table(ut3_develop.ut_runner.get_suites_info('UT3_USER', 'TC_JSON_SOURCE')) + where item_name = 'FROM_TABLE'; + ut.expect(l_actual).to_equal(l_expected).unordered(); + end; + + procedure runner_is_test is + begin + ut.expect(ut3_develop.ut_runner.is_test('UT3_USER', 'TC_INLINE', 'HALF')).to_be_true(); + ut.expect(ut3_develop.ut_runner.is_test('ut3_user', 'tc_json_source', 'from_table')).to_be_true(); + ut.expect(ut3_develop.ut_runner.is_test('UT3_USER', 'TC_INLINE', 'HAL')).to_be_false(); + end; + procedure times_json is begin set_other_session(); diff --git a/test/ut3_user/api/test_ut_test_cases.pks b/test/ut3_user/api/test_ut_test_cases.pks index 7af02dea8..72f0aa2a8 100644 --- a/test/ut3_user/api/test_ut_test_cases.pks +++ b/test/ut3_user/api/test_ut_test_cases.pks @@ -145,6 +145,16 @@ create or replace package test_ut_test_cases is --%endcontext + --%context(ut_runner) + + --%test(get_suites_info lists each --%testcase as a test and a --%testcasesource test once) + procedure runner_get_suites_info; + + --%test(is_test finds tests with --%testcase and --%testcasesource) + procedure runner_is_test; + + --%endcontext + --%context(dates and times) --%test(Converts date and time strings independent of NLS settings and session time zone)