diff --git a/docs/userguide/annotations.md b/docs/userguide/annotations.md index 13ed97a23..18401381f 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 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. | @@ -338,6 +340,259 @@ 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. + 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. +- 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 +- `{}` 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. + +```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`, or without arguments, gives a warning and the annotation is ignored. + +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 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. + +```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; +/ +``` + +The function (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; +``` + +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. +- 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 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. +- `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. + +!!! 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: + +| 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 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)): + +- **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 + +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 +1335,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 +2405,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..fa217a1dc 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) and [Testcasesource](annotations.md#testcasesource). + + ```sql linenums="1" set serveroutput on begin diff --git a/source/core/types/ut_executable.tpb b/source/core/types/ut_executable.tpb index 5d454989d..04f59baa3 100644 --- a/source/core/types/ut_executable.tpb +++ b/source/core/types/ut_executable.tpb @@ -55,7 +55,11 @@ 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_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; @@ -86,7 +90,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 +123,31 @@ 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 + 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; + 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 + -- 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 +155,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 +190,9 @@ 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_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 +203,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 +217,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..44545ce86 100644 --- a/source/core/types/ut_executable.tps +++ b/source/core/types/ut_executable.tps @@ -30,6 +30,19 @@ 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] + */ + call_arguments varchar2(4000 char), + /** + * Function of a --%testcasesource annotation + */ + call_source varchar2(4000 char), + /** + * 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, 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..900f57fbe 100644 --- a/source/core/types/ut_suite.tpb +++ b/source/core/types/ut_suite.tpb @@ -34,6 +34,80 @@ 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; + l_filter ut_integer_list; + + 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 + -- 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 + 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 + 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 +136,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..1ddc62b8e 100644 --- a/source/core/types/ut_test.tpb +++ b/source/core/types/ut_test.tpb @@ -174,5 +174,90 @@ 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_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 + begin + raise_application_error( + ut_utils.gc_invalid_test_case_source, 'The --%testcasesource function ' || self.item.call_source || ' ' || a_message || '.' + ); + 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); + 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 7590abc35..9c372d3da 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. + */ + 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..04137efb1 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,71 @@ 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; + + 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_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 doesn't change when an empty annotation is filled + l_case_no := l_case_no + 1; + l_arguments := trim(a_test_cases(l_position)); + if l_arguments is null then + add_annotation_ignored_warning( + 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; + 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 +424,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 +502,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 +758,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 +968,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 +992,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..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) @@ -29,17 +36,21 @@ 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 ( 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) = 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 a3ff6edfd..ad7466384 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; @@ -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: @@ -430,7 +460,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_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 3689d991e..f1f844f0e 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; @@ -294,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 @@ -497,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 @@ -505,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 new file mode 100644 index 000000000..ddbe52053 --- /dev/null +++ b/source/core/ut_test_case_json.pkb @@ -0,0 +1,334 @@ +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; + 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 + 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; + 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_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); + 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 + 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; + 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; + + -- 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 upper(l_parameters(i).parameter_name) = upper(a_key) then + l_result := l_parameters(i); + end if; + end loop; + 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)); + 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_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); + 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) := upper(l_parameters(i + 1).parameter_name); + end loop; + else + 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 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; + 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 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); + end loop; + + 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) || + 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..15c96e6d2 --- /dev/null +++ b/source/core/ut_test_case_json.pks @@ -0,0 +1,42 @@ +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. + * 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 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; + +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..cfd4d2ace --- /dev/null +++ b/source/core/ut_test_case_values.pkb @@ -0,0 +1,58 @@ +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_json is table of clob index by varchar2(4000 char); + type tt_filters is table of ut_integer_list index by varchar2(4000 char); + g_json tt_json; + g_filters tt_filters; + + 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_json(a_test_path varchar2) is + begin + g_json.delete(a_test_path); + end; + + procedure set_case_filters(a_filters ut_key_value_pairs) is + begin + 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; + + 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 + 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 new file mode 100644 index 000000000..3f008ed30 --- /dev/null +++ b/source/core/ut_test_case_values.pks @@ -0,0 +1,44 @@ +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 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_json(a_test_path varchar2, a_json clob); + + function get_json(a_test_path varchar2) return clob; + + 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 865e9e17c..77c7df68f 100644 --- a/source/core/ut_utils.pkb +++ b/source/core/ut_utils.pkb @@ -232,6 +232,58 @@ 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; + 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_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; + 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; + 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..8c2329724 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,22 @@ 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 (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 names or JSON keys), 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/install.sql b/source/install.sql index 3feca3a7d..81ac733b1 100644 --- a/source/install.sql +++ b/source/install.sql @@ -55,6 +55,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 +66,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..c85dad777 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 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..56f10c568 100644 --- a/test/ut3_tester/core/test_suite_builder.pkb +++ b/test/ut3_tester/core/test_suite_builder.pkb @@ -1968,5 +1968,197 @@ 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} (100, VIP)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); + end;]'; + end; + + procedure drop_test_case_args_package is + pragma autonomous_transaction; + begin + execute immediate 'drop package test_case_args'; + end; + + procedure testcase_every_case_is_a_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(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', '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( + '%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).not_to_be_like('%invalid arguments%'); + 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', '[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'); + --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('%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 09ff3c0b3..89f98ef34 100644 --- a/test/ut3_tester/core/test_suite_builder.pks +++ b/test/ut3_tester/core/test_suite_builder.pks @@ -182,6 +182,41 @@ 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 arguments) + + --%beforeall(create_test_case_args_package) + --%afterall(drop_test_case_args_package) + + --%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(Fills in the description, by position and by name, ignoring extra values and keys) + procedure testcase_json_arguments; + + --%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..0b1280251 100644 --- a/test/ut3_tester/core/test_ut_utils.pkb +++ b/test/ut3_tester/core/test_ut_utils.pkb @@ -372,6 +372,77 @@ 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( + '{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'[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 + 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..de7860c0e 100644 --- a/test/ut3_tester/core/test_ut_utils.pks +++ b/test/ut3_tester/core/test_ut_utils.pks @@ -124,6 +124,28 @@ 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, not case-sensitive) + procedure test_case_descr_placeholders; + + --%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) + 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..c2d4110bf --- /dev/null +++ b/test/ut3_user/api/test_ut_test_cases.pkb @@ -0,0 +1,1185 @@ +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; + 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;~' + ); + + 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(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([1]) + 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 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); + 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); + + --%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 + 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; + procedure no_parameters is + begin + null; + end; + procedure shared_source(a_amount number) is + begin + ut3_develop.ut.expect(a_amount).to_be_between(4, 10); + end; + procedure plain is + begin + null; + end; +end;~'; + + 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(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 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_JSON', 'TC_DISCOUNT_SOURCE', 'TC_INLINE', 'TC_SOURCES', 'TC_JSON_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; + + 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; + 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_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' + )) + ) 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( + '%